2009-11-05 95 views
1

我有一個類:在C#泛型參數調用委託

public class MyClass<T> 
{ 
    public string TestProperty { get; set; } 
} 

,我想創建一個代表就這一類的實例,如運行:

Action<MyClass<object>> myDelegate = myclass => myclass.TestProperty = "hello"; 

然而,上述代表不能用MyClass<object>以外的任何其他方式調用,例如MyClass<DateTime>MyClass<string>

我該如何定義委託或修改委託,以便我可以在MyClass<T>上執行委託,其中T是任何擴展了object的東西?

編輯:可以等到C#4,當這個成爲可能這就是(如果有的話,請還告訴我如何),但我更喜歡現在用它獲得3.5

編輯:我其實也有二等:

public class MyDerivedClass<T1, T2> : MyClass<T1> 
{ 
    public int OtherProp { get; set; } 
} 

理想ID喜歡用下面的語法來定義一些代表:

CreateDelegate<MyClass<object>>(mc => mc.TestProperty = "hello"); 
CreateDelegate<MyDerivedClass<object, object>>(mc => mc.OtherProp = 4); 

然後給出一個對象,我還想看看哪個委託參數匹配,然後運行它們

這可能嗎?我有什麼替代方案來創建這樣的代表?

感謝

回答

3

你可以創建一個接口來封裝的MyClass<T>您需要的成員:

interface IFoo 
{ 
    String TestProperty { get; set; } 
} 

然後改變你的委託來使用該接口:

Action<IFoo> myDelegate = myclass => myclass.TestProperty = "hello"; 

編輯:很顯然你會還需要這樣做:

public class MyClass<T> : IFoo 
{ 
    public String TestProperty { get; set; } 
} 
+0

感謝您的幫助,請參閱我的評論@Tony和更新後的問題 – 2009-11-05 23:26:07

+0

接口是答案,只是需要停止愚蠢! – 2009-11-06 11:04:58

4

編輯:思考它遠一點,我不相信C#4實際上將幫助你在這種情況下。你需要MyClass類型本身是變體,但它不能是因爲它是一個類。然而...

你可以寫一個通用的方法來回報你一個具體的行動:

public Action<MyClass<T>> NewTestPropertyDelegate<T>() 
{ 
    return myclass => myclass.TestProperty = "hello"; 
} 

編輯:我應該提到安德魯·黑爾的建議之前 - 但這裏使用一個基類另一種選擇,而不是一個接口。

public abstract class MyClass 
{ 
    public string TestProperty { get; set; } 
} 

public class MyClass<T> : MyClass 
{ 
    ... 
} 

然後使用Action<MyClass>

+0

嗯感謝您的信息,看起來像即將走出運氣。 ive用更多的信息更新了這個問題,認爲我可能會通過簡化問題略微誤導你:( – 2009-11-05 23:25:36

+0

我可以不使用表達式>代替,然後修改表達式到正確的T當應用它? – 2009-11-06 09:15:48

+0

@Andrew:嗯......可能......不確定,我會盡力記得在稍後再看看這個 – 2009-11-06 09:43:10

0

我知道這是一箇舊帖子,但我想它會幫助下一個可能想要這樣做的人。我對這個想法進行了修改,因爲我覺得它是一個非常理想的功能。我得到了有一個通用的參數委託做的工作如下:

公衆委託無效AppSettingsHandlerMethodSetKeyValue(字符串鍵,T值);

公共類AppSettingsHandler

{

公共CacheHandler(AppSettingsHandlerMethodSetKeyValue setAppSettingsVariable)

{

SetApplicationSettingsVariable =(AppSettingsHandlerMethodSetKeyValue)setAppSettingsVariable;

}

內部AppSettingsHandlerMethodSetKeyValue SetApplicationSettingsVariable {得到;組; }

內部空隙SetApplicationSetting(字符串鍵,T值)

{

SetApplicationSettingsVariable(鍵,值);

}

}

我希望有人認爲這很有幫助。我確定有人會對此有所評論,但它適用於我。