我有一个扩展方法,可以将字符串值转换为各种类型,看起来像这样:
public static T ToType<T> (this string value, T property)
{
object parsedValue = default(T);
Type type = property.GetType();
try
{
parsedValue = Convert.ChangeType(value, type);
}
catch (ArgumentException e)
{
parsedValue = null;
}
return (T)parsedValue;
}
Run Code Online (Sandbox Code Playgroud)
但是,我对调用该方法时的外观方式不满意:
myObject.someProperty = stringData.ToType(myObject.someProperty);
Run Code Online (Sandbox Code Playgroud)
仅仅为了获取属性的类型而指定属性似乎是多余的.我宁愿使用这样的签名:
public static T ToType<T> (this string value, Type type) { ... }
Run Code Online (Sandbox Code Playgroud)
并且T最终为类型类型.这会使通话变得更加清洁:
myObject.someProperty = stringData.ToType(typeof(decimal));
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试以这种方式调用时,编辑器会抱怨扩展方法的返回类型不能被使用.我可以将T链接到Type参数吗?
我错过了什么?
谢谢
Say*_*yse 17
这是你想要的?我已经为演员表无效的情况添加了额外的收益
Decimal i = stringName.ToType<Decimal>();
public static T ToType<T>(this string value)
{
object parsedValue = default(T);
try
{
parsedValue = Convert.ChangeType(value, typeof(T));
}
catch (InvalidCastException)
{
parsedValue = null;
}
catch (ArgumentException)
{
parsedValue = null;
}
return (T)parsedValue;
}
Run Code Online (Sandbox Code Playgroud)
编辑
修复安东评论的捷径
if (typeof(T).IsValueType)
return default(T);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29607 次 |
| 最近记录: |