因此,这里的代码,检查泛型类型在Action委托回调
public void DoSomething<T>(string key, Action<T> callback)
{
Type typeParameterType = typeof(T);
if (typeParameterType.Equals(typeof(string)))
{
callback("my string response");
}
if (typeParameterType.Equals(typeof(int)))
{
callback(1); // my int response
}
// etc...
}
但是,我得到的错误......我是新来的所有的C#泛型和代表的东西。
我得到的错误是,
Error 1 Delegate 'System.Action<T>' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'T'
对我来说其重要创造美丽的和有用的方法,这些方法简单,地道。
所以我很想实现这样上面的例子中,
int total = 0;
DoSomething<int>("doesn't matter", x => {
total = 10 + x; // i can do this because x is an INT!!! (:
});
string message = "This message is almost ";
DoSomething<int>("doesn't matter", x => {
message = "finished!!!"; // i can do this because x is an STRING!!! (:
});
但我坚持......请帮助!
============================================== =================================
正如dasblinkenlight指出,
重载是最干净大多数编译器友好的方式...我的API现在看起来,
DoSomething("doesn't matter", new Action<string>(x => {
message = "finished!!!"; // i can do this because x is an STRING!!! (:
}));
这是很小的代价,更容易理解。
感谢您的回答(:
==================================== ===========================================
做更多研究,我真的可以清理执行下列操作;
DoSomething("doesn't matter", (string x) => {
message = "finished!!!"; // i can do this because x is an STRING!!! (:
});
声明本:(串x)
现在编译器知道非常酷虎H?
然后我得到这个错误:的调用以下方法或属性之间暧昧:“ClassLibrary1.Class1。DoSomething(字符串,System.Action)'和'ClassLibrary1.Class1.DoSomething(string,System.Action )' –
Erik5388
@ Erik5388那么,如果你必须支持'对象'或子类,第二个技巧是行不通的。第一个技巧(转换为对象)有效吗? – dasblinkenlight
,因为它的使用方式如下:c.DoSomething(“whatever”,x => {//用x作为 的类型}); – Erik5388