检查操作委托回调中的泛型类型
本文关键字:泛型类型 回调 操作 检查 | 更新日期: 2023-09-27 18:32:13
所以这是代码,
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!!! (:
});
但是我被困住了...请帮忙!
===============================================================================================================================================================================================================================================
正如达斯布林肯莱特指出的那样,
重载是最干净、编译器友好的方法...我的 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)
现在编译器知道了!很酷吧?
特定类型(如 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));
你可以检查回调类型:
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...
}