[英]C# reflection cast to variable type
Just started studying reflection and im having a lot of issues. 刚刚开始研究反思,即时通讯有很多问题。 I want to cast to find the type of properties and then set them. 我想强制转换以找到属性的类型,然后进行设置。 So i wanted to cast to these properties type. 所以我想强制转换为这些属性类型。
protected override object Load(SqlDataReader dr)
{
object item = Activator.CreateInstance(klass);
foreach (var p in klass.GetProperties())
{
MethodInfo pSet = p.GetSetMethod();
Type pType= p.PropertyType;
object setParam = dr[p.Name];
object[] paramArray = (object[])Array.CreateInstance(pType, 1);
paramArray[0] = setParam;
pSet.Invoke(item, paramArray);
}
return item;
}
As they said you need to add your errors, but from what i see you have two problems: 正如他们所说,您需要添加错误,但是从我看来,您有两个问题:
You use klass
as Type instead of typeof(klass)
You try to cast a whole array to a new type - this can be solved using Array.ConvertAll
... but the easier way would be to just initialize a regular array using: object[] paramArray = new object[1]
. 您将klass
用作Type而不是typeof(klass)
尝试将整个数组转换为新类型-可以使用Array.ConvertAll
...解决,但是更简单的方法是使用object[] paramArray = new object[1]
:初始化常规数组object[] paramArray = new object[1]
。
good luck 祝好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.