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();
}
}
它说它不能从 bool 类型转换为 T,或 datetime 类型转换为 T.. 如何实现?
innerPrecess()
给我一个字符串。我想将其解析为给定参数的类型,然后将其返回。
最佳答案
您可以使用 Convert.ChangeType
来简化操作:
public static T Process<T>( string key) where T: IConvertible
{
return (T)Convert.ChangeType(key.InnerProcess(), typeof (T));
}
关于c#类型参数: How to Parse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17334693/