[英]Set property on a derived class of List<T> instantiated at runtime using reflection
I am using reflection to instantiate a custom class `class MyList : MyBaseClass, IList´:我正在使用反射来实例化一个自定义类`class MyList : MyBaseClass, IList´:
foreach (FieldInfo field in this.GetType().GetFields())
{
if (field.FieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() == typeof(MyList<>))
{
var elementType = field.FieldType.GetGenericArguments()[0];
var listType = typeof(MyList<>).MakeGenericType(elementType);
var valueToSet= Activator.CreateInstance(listType);
field.SetValue(this, valueToSet);
...
valueToSet.MyName = field.Name; // does not work because "valueToSet" does not recognize this property
...
}
}
The problem is, that the part valueToSet.MyName = field.Name
does not recognize the property MyName
that my custom class MyList<T>
has.问题是,部分valueToSet.MyName = field.Name
无法识别我的自定义类MyList<T>
具有的属性MyName
。 I also tried defining my MyList<T>
as class MyList<dynamic> : MyBaseClass, IList<dynamic>
but the valueToSet.MyName = field.Name
part throws now the error System.ArgumentException HResult=0x80070057 Message=Object of type objects.MyList 1[System.Object] cannot be converted to type objects.MyList 1[MyNameSpace.MyObjectType1]...
我还尝试将MyList<T>
定义为class MyList<dynamic> : MyBaseClass, IList<dynamic>
但valueToSet.MyName = field.Name
部分现在抛出错误System.ArgumentException HResult=0x80070057 Message=Object of type objects.MyList 1[System.Object] cannot be converted to type objects.MyList 1[MyNameSpace.MyObjectType1]...
Any hint on how to resolve this?有关如何解决此问题的任何提示? I would like to keep my original declaration without dynamics
我想保留没有dynamics
原始声明
Thanks in advance!提前致谢!
There are a few ways.有几种方法。 You can choose the one that you think is the most suitable for you.您可以选择您认为最适合您的那一款。
Keep using reflection继续使用反射
PropertyInfo myNameProperty = listType.GetProperty("MyName");
myNameProperty.SetValue(valueToSet, field.Name);
Use dynamic
:使用dynamic
:
dynamic valueToSet= Activator.CreateInstance(listType);
...
valueToSet.MyName = field.Name;
Cast to superclass投射到超类
And apparently, as you said in your comments, you can declare MyName
in MyBaseClass
.显然,正如您在评论中所说,您可以在MyBaseClass
声明MyName
。 This is an unusual thing to be able to do, but okay... Given that MyName
is declared in MyBaseClass
, you can cast valueToSet
to MyBaseClass
:这是一件不寻常的事情,但是可以……鉴于MyName
在MyBaseClass
声明,您可以将valueToSet
为MyBaseClass
:
((MyBaseClass)valueToSet).MyName = field.Name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.