假設你能夠改變MainClass
,我能想到的兩個選項:
- 增加提及
MainClass
當你創建一個ObjectA
實例。
- 就像你在評論中說的那樣,使用事件。
使用參考:
class MainClass
{
public int mode = 31416;
ObjectA obj;
public MainClass()
{
obj = new ObjectA(this);
}
public int GetMainClassMode()
{
return mode;
}
public void Test() {
Console.WriteLine("Calling test method inside obj");
obj.Test();
}
}
class ObjectA {
MainClass parent = null;
public ObjectA(MainClass parent)
{
this.parent = parent;
}
public void Test()
{
if (parent != null)
{
Console.WriteLine("Getting mode from 'parent' MainClass");
Console.WriteLine(string.Format("Mode = {0}", parent.GetMainClassMode()));
}
}
}
使用事件:
class MainClass
{
public int mode = 31416;
ObjectA obj = new ObjectA();
public MainClass()
{
obj.ValueReturnEvent += HandleValueReturnEvent;
}
public int GetMainClassMode()
{
return mode;
}
// Handle event, return data
private int HandleValueReturnEvent(object sender, EventArgs e)
{
return mode;
}
public void Test() {
Console.WriteLine("Calling test method inside obj");
obj.Test();
}
}
class ObjectA {
// delegate
public delegate int ReturnValueEventHandler(object sender, EventArgs args);
// event
public event ReturnValueEventHandler ValueReturnEvent;
public void Test()
{
// make sure at least one subscriber
if (ValueReturnEvent != null)
{
// note the event is returning a value
var myValue = ValueReturnEvent(this, null);
Console.WriteLine("Getting mode from 'parent' MainClass");
Console.WriteLine(string.Format("Mode = {0}", myValue));
}
}
}
在這兩種情況下,你會得到這樣的輸出:
Calling test method inside obj
Getting mode from 'parent' MainClass
Mode = 31416
我也會搜索這個,如果我可以但我不知道搜索條件,所以謝謝誰幫助! –
我假設你可以改變'ObjectA'? – BradleyDotNET
您正在尋找的編程概念被稱爲「範圍」。我建議先回顧一下這個概念,然後重點關注C#中的變量和方法範圍。 – Brandon