2013-09-22 52 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... 
}