c#类型参数:如何解析? publicstatict进程(此字符串键) 其中T:bool,string,DateTime { var tType=类型(T); if(tType==typeof(DateTime)) { return DateTime.Parse(key.InnerProcess()); } else if(tType==typeof(bool)) { 返回bool.Parse(key.InnerProcess()); } else if(tType==typeof(string)) { return key.InnerProcess(); } }

c#类型参数:如何解析? publicstatict进程(此字符串键) 其中T:bool,string,DateTime { var tType=类型(T); if(tType==typeof(DateTime)) { return DateTime.Parse(key.InnerProcess()); } else if(tType==typeof(bool)) { 返回bool.Parse(key.InnerProcess()); } else if(tType==typeof(string)) { return key.InnerProcess(); } },c#,asp.net,oop,c#-4.0,c#-3.0,C#,Asp.net,Oop,C# 4.0,C# 3.0,它说它不能从bool到T,或者从datetime到T进行类型转换。。 如何做到这一点 innerProcess()给了我一个字符串。我想将其解析为给定参数的类型,然后返回它。编译器不会试图理解代码来证明返回的是t。唯一的方法是添加一个box/unbox(用于值类型,而不是字符串),不幸的是: public static T Process<T>(this string key) where T:bool,string, DateTime { v

它说它不能从bool到T,或者从datetime到T进行类型转换。。 如何做到这一点


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

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

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();
        }
    }

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

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

return (T)(object)DateTime.Parse(...etc...);
publicstatict进程(字符串键),其中T:IConvertible
{
return(T)Convert.ChangeType(key.InnerProcess(),typeof(T));
}

您的类型参数约束无论如何都不起作用。T需要是所有的人。不幸的是,这在这里是互斥的。没有一个约束是有效的:如果指定一个类型作为约束,它必须是接口或未密封的类
bool
DateTime
是结构,而
string
是一个密封类。+1,这将适用于实现
System.IConvertible
的任何类型T。请注意,需要实现
IConvertible
的不是
T
,而是
ChangeType()
的第一个参数。实际上,
T
必须是
IConvertible
提供转换的类型,尽管没有明确的方法将其放入约束中。
public static T Process<T>( string key) where T: IConvertible
{
    return (T)Convert.ChangeType(key.InnerProcess(), typeof (T));
}