2016-02-04 33 views
1

我可以訪問包含委託內委託的對象嗎?c#從委託函數訪問所有者對象

例如

class Salutation { 

    public string OtherParty {get; set;} 
    public AddressDelegate GreetingDelegate {get; set;} 

} 

public delegate void AddressDelegate(); 

則...

void Main() { 
    Salutation hello = new Salutation { 
     OtherParty = "World", 
     GreetingDelegate = new AddressDelegate(HelloSayer) 
    }; 

    hello.GreetingDelegate(); 
} 

private void HelloSayer() { 
    Console.WriteLine(string.Format("Hello, {0}!", OtherParty)); 
} 

所以是有可能的HelloSayer函數內參照OtherParty財產的稱呼類的,或者我需要傳遞數據作爲參數傳遞給功能?

回答

1
static void Main(string[] args) 
    { 
     Salutation hello = new Salutation(); 
     hello.OtherParty = "World"; 
     hello.GreetingDelegate = new AddressDelegate(HelloSayer); 

     hello.GreetingDelegate(hello.OtherParty); 
     Console.ReadKey(); 
    } 

    public delegate void AddressDelegate(string otherParty); 

    private static void HelloSayer(string otherParty) 
    { 
     Console.WriteLine(string.Format("Hello, {0}!", otherParty)); 
    } 

像安德烈說的,你需要通過它,這裏是例子。

2

你需要通過它。代表對業主對象一無所知。因爲它不是一個所有者,所以它只是一個碰巧對這個委託進行引用的對象。