我想將委托宣告傳遞給一個類,該類稍后將由另一個類分配,然后由第一個類呼叫。我在下面代碼中指示的行中得到了 NullReferenceException。如何更改代碼以獲得所需的行為?
class FirstClass
{
public Func<bool> funct;
public FirstClass(Func<bool> funct)
{
this.funct = funct;
}
public void callFunc()
{
funct.Invoke(); // NullReferenceException
}
}
class Program
{
public static Func<bool> testFunction;
static void Main(string[] args)
{
FirstClass firstClassInstance = new FirstClass(testFunction);
var secondClassInstance = new SecondClass();
firstClassInstance.callFunc();
}
}
class SecondClass
{
public SecondClass()
{
Program.testFunction = isManipUnderCursor;
}
private bool isManipUnderCursor()
{
return true;
}
}
uj5u.com熱心網友回復:
如果要呼叫 的當前值Program.testFunction,請呼叫Program.testFunction
public void callFunc()
{
Program.testFunction?.Invoke();
}
或者您提供一個代碼來更改 FirstClass.funct 的值,然后呼叫它:
class FirstClass{
...
public void ChangeFuncTo(Func<bool> newFunc){
funct = newFunc;
}
...
}
FirstClass firstClassInstance = new FirstClass(testFunction);
var secondClassInstance = new SecondClass();
firstClassInstance.ChangeFuncTo(Program.funct);
你安排的這整件事在結構、封裝和連貫的類職責方面相當糟糕。如果您可以針對真正的目標發布一個實際用例,那就太好了,因此我們可以提出建議,但通常您應該將函式視為資料;如果您在完成構造和使用其他物件后只知道希望 firstclass 的 func 執行什么操作,請不要依賴靜態來傳遞新的 func;提供并呼叫第一個類的方法來設定新行為。static努力在你的代碼中找到避免的方法。
//we need to make FirstClass for some reason, before we can generate the fun it will use
FirstClass firstClassInstance = new FirstClass();
//second class is a func generator
var secondClassInstance = new SecondClass();
//now we can generate the func and set it
firstClassInstance.ChangeFuncTo(secondClassInstance.GetNewFunc());
或者
//second class is a func generator, it can generate before firstclass is made
var secondClassInstance = new SecondClass();
//now we can generate the func and set it
FirstClass firstClassInstance = new FirstClass(secondClassInstance.GetFunc());
在 C# 中,您不能“通過更改其他一些簡單變數指向的內容來更改一些簡單變數指向的內容”。用良好的舊資料更簡單地解釋它:
string first = "this is the first string";
string second = first
first = "something else";
second仍將參考“這是第一個字串”的值。當您建立額外的參考時,它們不會鏈接。當你寫string first = "this is the first string";它時,它會給我們這樣的記憶:
first --> "this is the first string"
然后你寫string second = first它給我們這樣的記憶:
first --> "this is the first string" <-- second
最后你寫給first = "something else"我們這樣的記憶:
"this is the first string" <-- second
first --> "something else"
變化first從不受影響second。撰寫string second = first時不會在記憶體中出現鏈式參考,如下所示:
second --> first --> "this is the first string"
這樣改變first會導致second看到它:
second --> first --. //"this is the first string" garbage collected
`-> "something else"
uj5u.com熱心網友回復:
當您傳遞testFunction給 時FirstClass,它為空,因為testFunction尚未初始化或分配。在這種情況下,傳遞的參考不指向值的未來家,但它指向 null 并且總是會。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419863.html
標籤:
