是否有任何通用的Parse()函数将使用parse将字符串转换为任何类型?

Kar*_*rim 79 c# string parsing type-conversion

我想将字符串转换为泛型类型int,date或者long基于泛型返回类型.

基本上这样的函数Parse<T>(String)返回一个类型的项T.

例如,如果传递了一个int,那么函数应该在int.parse内部完成.

Ani*_*Ani 114

System.Convert.ChangeType

根据您的示例,您可以:

int i = (int)Convert.ChangeType("123", typeof(int));
DateTime dt = (DateTime)Convert.ChangeType("2009/12/12", typeof(DateTime));
Run Code Online (Sandbox Code Playgroud)

要满足"通用返回类型"要求,您可以编写自己的扩展方法:

public static T ChangeType<T>(this object obj)
{
    return (T)Convert.ChangeType(obj, typeof(T));
}
Run Code Online (Sandbox Code Playgroud)

这将允许您:

int i = "123".ChangeType<int>();
Run Code Online (Sandbox Code Playgroud)

  • MSDN说它只是一个包装器,它在源对象上找到正确的转换方法,要求它实现IConvertible接口. (7认同)
  • @Liam:不,它的'obj`必须是`IConvertible`,但是没有办法在编译时指定它. (2认同)

Pra*_*eep 18

看起来我已经来不及回答这个帖子了.但这是我的实施:

基本上,我已经为Object类创建了一个Extention方法.它处理所有类型,即可空,类和结构.

 public static T ConvertTo<T>(this object value)
           {
               T returnValue;

               if (value is T variable)
                   returnValue = variable;
               else
                   try
                   {
                       //Handling Nullable types i.e, int?, double?, bool? .. etc
                       if (Nullable.GetUnderlyingType(typeof(T)) != null)
                       {
                           TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
                           returnValue = (T) conv.ConvertFrom(value);
                       }
                       else
                       {
                           returnValue = (T) Convert.ChangeType(value, typeof(T));
                       }
                   }
                   catch (Exception)
                   {
                       returnValue = default(T);
                   }

               return returnValue;
           }
Run Code Online (Sandbox Code Playgroud)

  • 恕我直言,这是更好的答案,因为它还包含“可为空”方面 (2认同)

Ale*_*man 10

System.Convert.ChangeType不会转换为任何类型.想一想以下内容:

  • 可空类型
  • 枚举
  • 指导等

使用ChangeType的这种实现可以实现这些转换.


Ber*_*hus 8

从 C# 11 和 .Net 7 开始,由于接口上的静态方法,这现在成为可能并得到支持。

新的IParsable<TSelf>提供了静态 Parse 方法:

abstract static TSelf Parse(string s, IFormatProvider? provider);
Run Code Online (Sandbox Code Playgroud)

所有常见值类型(int、decimal、Guid 等)都实现了此接口,但有一个例外:Nullable<T>没有,因为显然T不能假定 in nullable 实现了IParsable<T>。但这在实践中不应该成为问题(下面提供的示例)。

这是一个使用它的简单扩展方法:

public static T Parse<T>(this string s, IFormatProvider? provider = null) where T : IParsable<T>
{
    return T.Parse(s, provider);
}
Run Code Online (Sandbox Code Playgroud)

因此,例如, 的调用myString.Parse<int>将直接调用而int.Parse无需装箱,或者需要在运行时检查类型。

用法示例:

string s = "5";
int i = s.Parse<int>();
double d = s.Parse<double>();

// Need Nullable<T> support? Just use the null-conditional operator.
string? s2 = null;
decimal? d2 = s2?.Parse<decimal>();
Run Code Online (Sandbox Code Playgroud)


Eon*_*dan 6

Pranay答案的清洁版

public static T ConvertTo<T>(this object value)
{
    if (value is T variable) return variable;

    try
    {
        //Handling Nullable types i.e, int?, double?, bool? .. etc
        if (Nullable.GetUnderlyingType(typeof(T)) != null)
        {
            return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value);
        }

        return (T)Convert.ChangeType(value, typeof(T));
    }
    catch (Exception)
    {
        return default(T);
    }
}
Run Code Online (Sandbox Code Playgroud)