所以这里是代码,
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)
现在编译器知道了!很酷吧?