![](/img/trans.png)
[英]What's the difference between a static struct method and a static class method?
[英]What is the proper way to provide an object to a static class's static method?
例如,如果我有一個 static class:
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
需要一個 object,但問題是我不直接從我的實例 class 調用Method_4
。 實例 class 僅調用Method_1
,如果我將 object 傳遞給Method_1
,我必須在調用鏈中的每個方法中不必要地提供該對象的類型作為參數 - Method_1 -> Method_2 -> Method_3 -> Method_4
中間方法都不需要使用 object。
將 object 提供給Method_4
的正確方法是什么。 我應該在所有方法中包含它的參數嗎?
如果需要 object,那么它並不是“不必要地”傳遞它——它必然是傳遞它。 所以:您將需要為所有這些添加一個參數並將其傳遞(或者:考慮使這些成為所需類型的實例方法)。
所以
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 }
我確實建議將它作為參數添加到所有方法中:
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
時存儲的值,這可能會導致不可預知的副作用)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.