我有一个扩展方法是工作确定投字符串值成各种类型,这看起来是这样的:
I have an extension method that is working ok to cast string values into various types, which looks something like this:
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;
}
我不满调用方法时,这看起来的样子,但是:
I'm unhappy about the way this looks when calling the method, however:
myObject.someProperty = stringData.ToType(myObject.someProperty);
指定酒店仅获得属性的类型似乎是多余的。我宁愿用一个签名是这样的:
Specifying the property just to obtain the property's type seems redundant. I would rather use a signature like this:
public static T ToType<T> (this string value, Type type) { ... }
和为T最终成为类型的类型。这将拨打电话更清洁的:
and have T end up to be the Type of type. This would make calls much cleaner:
myObject.someProperty = stringData.ToType(typeof(decimal));
当我尝试调用这种方式,但是,编辑抱怨说,扩展方法的返回类型不能从使用推导。我可以链接T可Type参数?
When I try to call this way, however, the editor complains that the return type of the extension method can't be infered from usage. Can I link T to the Type argument?
我在想什么?
感谢
这是你在找什么?我已经添加了一个额外的渔获量情况下的转换无效也
Is this what you are looking for? I've added an extra catch for cases where the cast isn't valid also
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;
}
修改
快捷方式来解决安东的评论
a shortcut approach to fix Anton's comment
if (typeof(T).IsValueType)
return default(T);