c#类型参数: How to Parse?

标签 c# asp.net oop c#-4.0 c#-3.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();
        }
    }

它说它不能从 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/

相关文章:

c# - 什么时候使用 HttpBindNever 属性?

c# - asp.net超链接无法定位url

c# - 使用c#获取onload隐藏字段值

java - 使用继承类名初始化抽象类列表的更好方法

javascript - 防止动态添加 "instance variables"的能力 Javascript OOP

javascript - 在 React-Redux 应用程序中应将实用函数放在哪里?

c# - 为什么编译器对这行代码有问题呢?

c# - 当多个用户登录时,一段时间后 ASP.Net C# 应用程序变慢

c# - Xamarin RestSharp POST 方法抛出请求超时错误和名称解析错误

asp.net - 错误 : The application which this project type is based on was not found