2013-09-22 49 views
1

因此,这里的代码,检查泛型类型在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?

回答

1

特定类型如intstring不能转换为T,但object可以。这应该工作:

if (typeParameterType.Equals(typeof(string))) 
{ 
    callback((T)((object)"my string response")); 
} 
if (typeParameterType.Equals(typeof(int))) 
{ 
    callback((T)((object)1)); // my int response 
} 

然而,这是一个有些奇怪,你需要做到这一点首先:而不是通过篮球与仿制药跳,你可以更加妥善地处理这个问题,多种方法:

public void DoSomething(string key, Action<int> callback) { 
    callback(1); 
} 
public void DoSomething(string key, Action<string> callback) { 
    callback("my string response"); 
} 

现在你可以调用这些方法是这样的:

DoSomething("hello", new Action<int>(x => Console.WriteLine("int: {0}", x))); 
DoSomething("world", new Action<string>(x => Console.WriteLine("str: {0}", x))); 

或像这样:

DoSomething("hello", (int x) => Console.WriteLine("int: {0}", x)); 
DoSomething("world", (string x) => Console.WriteLine("str: {0}", x)); 
+0

然后我得到这个错误:的调用以下方法或属性之间暧昧:“ClassLibrary1.Class1。DoSomething(字符串,System.Action )'和'ClassLibrary1.Class1.DoSomething(string,System.Action )' – Erik5388

+0

@ Erik5388那么,如果你必须支持'对象'或子类,第二个技巧是行不通的。第一个技巧(转换为对象)有效吗? – dasblinkenlight

+0

,因为它的使用方式如下:c.DoSomething(“whatever”,x => {//用x作为 的类型}); – Erik5388

0

您可以检查回调类型:

public void DoSomething<T>(string key, Action<T> callback) 
{ 
    var action1 = callback as Action<string>; 
    if (action1 != null) 
    { 
     action1("my string response"); 
     return; 
    } 

    var action2 = callback as Action<int>; 
    if (action2 != null) 
    { 
     action2(1); // my int response 
     return; 
    } 
    // etc... 
}