首页 > 解决方案 > 如何在接口的空列表中获取对象类型

问题描述

考虑:

public interface I
{
    int InterfaceProperty {get;set;}
}

public class C1 : I
{
    public int InterfaceProperty {get;set;}
    public int Class1Property {get;set;}
}

public class C2 : I
{
    public int InterfaceProperty {get;set;}
    public int Class2Property {get;set;}
}

//In some other class:
public List<I> L;
void somemethod()
{
    this.L = new List<I>();
    this.L.Add(new C1());   //add some C1s into the list
    SomeMethodToGetProperties(L);
    this.L = new List<I>();
    this.L.Add(new C2());  //add some C2s into the list
    SomeMethodToGetProperties(L);
}

我需要 SomeMethodToGetProperties 来获取 C1 或 C2 的属性列表。即,第一次调用返回InterfaceProperty 和Class1Property,第二次调用返回InterfaceProperty 和Class2Property。

我不能使用列表中的对象,因为列表可能是空的。我在列表上尝试了反射,但这只给了我接口的属性。

编辑:我写它的原始方式无效。你不能做

this.L = new List<C1>()

你只能做类似的事情

this.L = new List<I>();
this.L.Add(new C1());

列表本身的元数据似乎无法满足我的需求。所以我创建了第二个变量来保存每次更改列表内容时设置的列表中保存的项目类型。

标签: c#listreflectioninterface

解决方案


要获取列表的实际类型:

Type listType = this.L.GetType();

要获取它可以包含的对象类型:

Type elementType = listType.GetGenericArguments().Single();

要获取该类型的属性:

var properties = elementType.GetProperties();

推荐阅读