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

How to reflect on a different delegate for a string type in C#?

如何为 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>; 
    }

这应该有效:

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"