Kar*_*rim 79 c# string parsing type-conversion
我想将字符串转换为泛型类型int
,date
或者long
基于泛型返回类型.
基本上这样的函数Parse<T>(String)
返回一个类型的项T
.
例如,如果传递了一个int,那么函数应该在int.parse
内部完成.
Ani*_*Ani 114
根据您的示例,您可以:
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)
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)
从 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)
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)
归档时间: |
|
查看次数: |
32629 次 |
最近记录: |