1

所以这里是代码,

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)

现在编译器知道了!很酷吧?

4

2 回答 2

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));
于 2013-09-22T04:07:59.850 回答
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...
}
于 2013-09-22T04:19:25.733 回答