通用型铸造法(.NET) [英] Generic type casting method (.Net)
本文介绍了通用型铸造法(.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图创建一个通用的方法来投的对象,但似乎无法破解的栗子。 (这是星期五下午3点,是一个漫长的一周)
I'm trying to create a generic method to cast an object, but can't seem to crack that chestnut. (It's Friday 3pm, been a long week)
好了,我有这样的情况:
Ok, so I have this scenario:
// We have a value (which .net sets as a double by default)
object obj = 1.0;
// We have the target type as a string, which could be anything:
// say string sometType = "System.Decimal"
Type type = Type.GetType(someType);
// I need a generic way of casting this
object castedObj = (xxx) obj;
我怎么能投的对象一般不会产生的if-else-staments无尽的数量?
How can I cast that object generically without creating an endless number of if-else-staments?
推荐答案
您可以使用 Convert.ChangeType 方法,如果你使用的类型实现 IConvertible (所有基本类型做)
You can use Convert.ChangeType method, if the types you use implement IConvertible (all primitive types do).
Convert.ChangeType(value, targetType);
这篇关于通用型铸造法(.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文