c# - 如何使用反射设置类型为 List<CustomClass> 的属性

标签 c# reflection .net-2.0

已经有一个类似的question但它似乎并没有询问问题所暗示的情况。

用户询问列表中的自定义类,但他的列表对象是字符串类型。

我有一个包含 Bars 列表的 Foo 类:

    public class Foo : FooBase
    { 
       public List<Bar> bars {get; set;} 
       public Foo() {}
    }

    public class Bar
    {
       public byte Id { get; set; } 
       public byte Status { get; set; } 
       public byte Type { get; set; } 
       public Bar(){} 
    }

我通过 Activator.CreateInstance() 使用反射实例化 Foo。现在我需要用 Bar 对象填充该条形列表。

Foo是使用

获得的
Assembly.GetAssembly(FooBase).GetTypes().Where(type => type.IsSubclassOf(FooBase));

Bar 是同一个Assembly 中的公共(public)类。我需要以某种方式获得那种类型。我似乎看不到 Foo 中包含的列表类型是什么。我知道这是一个列表。我将列表属性视为 List`1。

我需要查看列表包含的对象类型并相应地进行处理。

最佳答案

正文

List`1

是在引擎盖下编写泛型的方式 - 意思是“列出 1 个泛型类型 arg,又名 List<>”。如果你有 PropertyInfo , 你应该被设置;这将是封闭的通用 List<Bar> .是不是你要找Bar 只是这个?

如果是这样,这将在各种问题中进行讨论,包括 this one ;复制 key 位(我更喜欢针对 IList<T> 进行编码,因为它处理一些边缘情况,例如 inheriting from List<T> ):

static Type GetListType(Type type) {
    foreach (Type intType in type.GetInterfaces()) {
        if (intType.IsGenericType
            && intType.GetGenericTypeDefinition() == typeof(IList<>)) {
            return intType.GetGenericArguments()[0];
        }
    }
    return null;
}

关于c# - 如何使用反射设置类型为 List<CustomClass> 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1312233/

相关文章:

C++:有没有办法让这个反射宏与 IntelliSense 一起工作?

c# - String.IndexOf 方法的表达式树

java - Android:是否可以下载Android自定义View的类(它是LinearLayout的扩展)并在运行时实例化它?

c# - 在 xml 文件中搜索数据的最佳方式?

c# - 如何读取 C# 测试项目中的 app.config 值

c# - 如何使用 SmartFormat.NET 使用集合中项目的属性

asp.net - log4Net EventlogAppender 不适用于 Asp.Net 2.0 网站?

.net - 在托管 C++ 中检测 Debug模式

c# - 如何避免 ref 参数?

c# - 如何在 AngularJS 中将参数传递给 DELETE?