所以这是代码,
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)
现在编译器知道了!很酷吧?
答案 0 :(得分:1)
int
和string
等特定类型无法转换为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));
或者像这样:
{{1}}
答案 1 :(得分: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...
}