我希望能夠從此 中的所有方法引用 類的 Reaction 對象> 類。我在第一個事件偵聽器方法中聲明了 對象。然而,第二個事件偵聽器無法訪問該類的實例,我不知道如何修復它。EquationClassCalculatorPageReaction我嘗試將第一種方法更改為public,但錯誤仍然存在。private void ExampleListenerMethodOne(object sender, RoutedEventArgs e){ var Reaction = new EquationClass("Example"); Reaction.species = Reaction.MakeAndReturnSpeciesArray();}public void ExampleListenerMethodTwo(object sender, RoutedEventArgs e){ Console.WriteLine(Reaction.species); //Here is the 'Does not exist //in current context error'}我希望能夠從任何地方訪問該對象,但我不能。 我從 Visual Studio 收到 “當前上下文中不存在錯誤”。我已閱讀其他相關問題,但找不到解決方案。
1 回答

絕地無雙
TA貢獻1946條經驗 獲得超4個贊
只需將其轉變為財產即可。在這里,該類實例化了一個 Reaction 類型的新變量(以及您需要執行的任何操作)。因此,對于下面需要它的兩個方法來說,myReaction 變量處于類級別范圍內。以前,您的變量位于方法范圍內,這意味著它不能在方法之外使用。代碼塊中定義的變量也有一個塊作用域,例如 if 語句,其中變量在 if 語句中定義。
public class MyClass
{
public Reaction myReaction { get; set; }
public MyClass()
{
myReaction = new EquationClass("Example");
}
private void ExampleListenerMethodOne(object sender, RoutedEventArgs e)
{
myReaction.species = Reaction.MakeAndReturnSpeciesArray();
}
public void ExampleListenerMethodTwo(object sender, RoutedEventArgs e)
{
Console.WriteLine(Reaction.species);
}
}
- 1 回答
- 0 關注
- 181 瀏覽
添加回答
舉報
0/150
提交
取消