c#类型参数:如何解析?

Bil*_*ani 2 c# asp.net oop c#-3.0 c#-4.0

public static T Process<T>(this string key)
        where T:bool,string, DateTime
    {
        var tType = typeof(T);

        if(tType == typeof(DateTime))
        {
            return DateTime.Parse(key.InnerProcess());
        }
        else if(tType == typeof(bool))
        {
            return bool.Parse(key.InnerProcess());
        }
        else if(tType == typeof(string))
        {
            return key.InnerProcess();
        }
    }
Run Code Online (Sandbox Code Playgroud)

它说它不能从bool到T或从datetime到T的类型转换.如何实现这一目标?

innerPrecess()给我一个字符串.我想将它解析为给定参数的类型,然后返回它.

cuo*_*gle 6

您可以使用Convert.ChangeType更简单:

public static T Process<T>( string key) where T: IConvertible
{
    return (T)Convert.ChangeType(key.InnerProcess(), typeof (T));
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 5

编译器不会试图理解代码来证明你返回的一个T.唯一的方法是不幸地添加一个box/unbox(对于值类型,而不是字符串):

return (T)(object)DateTime.Parse(...etc...);
Run Code Online (Sandbox Code Playgroud)

就个人而言,我建议只使用单独的非泛型方法,除非有充分的理由在这里使用泛型.