向静态类的静态方法提供对象的正确方法是什么?

时间:2021-04-15 12:02:03

标签: c#

例如如果我有一个静态类:

static class A
{

static int Method_1(){ Method_2(); }
static int Method_2(){ Method_3(); }
static int Method_3(){ Method_4(); }
static int Method_4() {  // Need to use the object here only  }

}

这里,Method_4 需要一个对象,但问题是我不直接从我的实例类调用 Method_4。实例类只调用 Method_1,如果我将对象传递给 Method_1,我必须在调用链中的每个方法中不必要地提供该对象的类型作为参数 - Method_1 -> Method_2 -> Method_3 -> 方法_4

中间方法都不需要使用对象。

将对象赋予 Method_4 的正确方法是什么。我应该在所有方法中都包含它的参数吗?

2 个答案:

答案 0 :(得分:3)

如果需要该对象,那么它不是“不必要地”传递它——而是必然传递它。所以:您将需要向所有这些添加一个参数并将其传递(或者:考虑使它们成为所需类型的 instance 方法)。

所以

static int Method_1(Whatever thing){ Method_2(thing); }
static int Method_2(Whatever thing){ Method_3(thing); }
static int Method_3(Whatever thing){ Method_4(thing); }
static int Method_4(Whatever thing) {  // Need to use the object here only  }

答案 1 :(得分:2)

我确实建议将其作为参数添加到所有方法中:

static class A
{
static int Method_1(object x){ Method_2(x); }
static int Method_2(object x){ Method_3(x); }
static int Method_3(object x){ Method_4(x); }
static int Method_4(object x) {  Console.WriteLine(x);  }
}

或者,您也可以将其存储在私有字段中:

static class A
{
private static object field;
static int Method_1(object x){ field = x; Method_2(); }
static int Method_2(){ Method_3(); }
static int Method_3(){ Method_4(); }
static int Method_4() {  Console.WriteLine(field );  }

}

但这有两个严重的缺点:首先,您的代码不再是线程安全的。此外,如果您想在某个时候直接调用 Method_4,您会遇到问题(因为仍然存在上次调用 Method_1 时存储的值,这可能会导致不可预测的副作用)。< /p>

相关问题