【问题标题】:How to reflect on a different delegate for a string type in C#?如何在 C# 中反映字符串类型的不同委托?
【发布时间】:2020-09-11 11:10:59
【问题描述】:

如何在 C# 中为字符串类型反映不同的委托?

我试图让它恢复为字符串的“ToString”

private static Func<string, T> TryGetParser<T>()
    {
        return typeof(T).GetMethod("Parse", new Type[] { typeof(string) })
            .CreateDelegate(typeof(Func<string, T>)) as Func<string, T>; 
    }

【问题讨论】:

  • different delegate 是什么意思?你想得到什么?
  • 我试图让它恢复为字符串的“ToString”
  • “恢复到 ToString”是什么意思?

标签: c# generics reflection delegates


【解决方案1】:

这应该可行:

private static Func<string, T> TryGetParser<T>()
{
    if(typeof(T) == typeof(string))
    {
        return s => (T)(object)s;
    }
    return typeof(T).GetMethod("Parse", new Type[] { typeof(string) })
        .CreateDelegate(typeof(Func<string, T>)) as Func<string, T>;
}

var parser = TryGetParser<string>();    
var foo = parser("bar"); // foo = "bar"

【讨论】:

  • 非常感谢,我尝试将 T 转换为 String 但没有成功,仍然不确定为什么 object 可以作为第二次转换,感谢您提供这么好的答案
  • 正如error docs 所说,发生此错误是因为T 可以是任何东西,编译器找不到“任何东西”和字符串之间的预定义转换。同时你可以欺骗它 - 一切都可以转换为对象。您可以尝试将 cast 对象作为任何对象(因为一切都是对象 =),但存在运行时错误的风险。
  • 谢谢这真的帮助我理解!
  • @user1688726 很高兴为您提供帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2021-06-19
相关资源
最近更新 更多