在 List<T> 的派生类上设置属性使用反射在运行时实例化 [英] Set property on a derived class of List&lt;T&gt; instantiated at runtime using reflection

查看:30
本文介绍了在 List<T> 的派生类上设置属性使用反射在运行时实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用反射来实例化一个自定义类`class MyList : MyBaseClass, IList´:

I am using reflection to instantiate a custom class `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
      ...
   }
}

问题是,部分 valueToSet.MyName = field.Name 无法识别我的自定义类 MyList 的属性 MyName代码> 有.我还尝试将我的 MyList 定义为 class MyList: MyBaseClass, IListvalueToSet.MyName = field.Name 部分现在抛出错误 System.ArgumentException HResult=0x80070057 Message=Object of type objects.MyList 1[System.Object] 无法转换为类型对象.MyList 1[MyNameSpace.MyObjectType1]...

The problem is, that the part valueToSet.MyName = field.Name does not recognize the property MyName that my custom class MyList<T> has. 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]...

有关如何解决此问题的任何提示?我想保留没有 dynamics
的原始声明提前致谢!

Any hint on how to resolve this? I would like to keep my original declaration without dynamics
Thanks in advance!

推荐答案

有几种方法.您可以选择您认为最适合您的那个.

There are a few ways. You can choose the one that you think is the most suitable for you.

继续使用反射

PropertyInfo myNameProperty = listType.GetProperty("MyName");
myNameProperty.SetValue(valueToSet, field.Name);

使用动态:

dynamic valueToSet= Activator.CreateInstance(listType);
...
valueToSet.MyName = field.Name;

转换为超类

显然,正如您在评论中所说,您可以在 MyBaseClass 中声明 MyName.这是一件不寻常的事情,但是可以...鉴于 MyNameMyBaseClass 中声明,您可以将 valueToSet 转换为MyBaseClass:

And apparently, as you said in your comments, you can declare MyName in MyBaseClass. 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:

((MyBaseClass)valueToSet).MyName = field.Name;

这篇关于在 List<T> 的派生类上设置属性使用反射在运行时实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆