从C#中的未知类型进行强制转换 [英] Cast from unknown type in c#
问题描述
我有一个对象,其中包含一个字符串值和一个字段中的原点类型.
I have a object that contain a value in string and a origin Type that is in a field.
class myclass
{
public string value;
public Type type;
}
myclass s=new myclass();
s.value = "10";
s.type = typeof(int);
Type tt = s.type;
row.Value[ind]= s[0].value as tt; //i have error here
如何通过该类型转换值.
How can i cast an value by that's type.
推荐答案
基本上,您的方案是要使用存储在变量中的类型进行类型转换.您只能像这样在运行时这样做:
Basically your scenario is that you want to type cast with the type stored in a variable. You can only do that at runtime like this :
myclass s=new myclass();
s.value = "10";
s.type = typeof(int);
var val = Convert.ChangeType(s.value, s.type);
但是由于转换是在运行时完成的,因此您不能将变量val存储在任何整数集合中,即 List< int>
,甚至不能进行 int another = val
,在编译时是coz,类型未知,由于同样明显的原因,您也会遇到编译错误.
but since the conversion is done at runtime, you cannot store the variable val in any integeral collection i.e. List<int>
or even you cannot do int another = val
, coz at complie time, the type is not known yet, and you will have compilation error, again for same obvious reason.
在稍微复杂的情况下,如果必须强制转换为 User-Defined dataType
,并且想要访问其不同的属性,则不能照原样进行.让我来演示一下您的代码:
In a little complex scenario, if you had to typecast to a User-Defined dataType
and you wanted to access its different properties, you cannot do it as is. Let me demonstrate with few modifications to your code :
class myclass
{
public object value;
public Type type;
}
还有另一个:
class myCustomType
{
public int Id { get; set; }
}
现在您要做:
myclass s = new myclass();
s.value = new myCustomType() { Id = 5 };
s.type = typeof(myCustomType);
var val = Convert.ChangeType(s.value, s.type);
现在,如果您执行 val.Id
,它将无法编译.您必须使用动态关键字或通过如下所示的反射来检索它:
now if you do val.Id
, it won't compile. You must retrieve it either by using dynamic keyword or by reflection like below:
var id = val.GetType().GetProperty("Id").GetValue(val);
您可以遍历customType(类)的所有可用属性并检索它们的值.
you can iterate over all the available properties of your customType (class) and retrieve their values.
要通过 dynamic
关键字进行检索,请直接执行以下操作:
for retrieving it through dynamic
keyword, directly do this:
dynamic val = Convert.ChangeType(s.value, s.type);
int id = val.Id;
并且编译器不会哭.(是的,但是不会有任何智能感知).
and compiler won't cry. (Yes there won't be any intellisense though)
这篇关于从C#中的未知类型进行强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!