c# - 如何在接口的空列表中获取对象类型
问题描述
考虑:
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());
列表本身的元数据似乎无法满足我的需求。所以我创建了第二个变量来保存每次更改列表内容时设置的列表中保存的项目类型。
解决方案
要获取列表的实际类型:
Type listType = this.L.GetType();
要获取它可以包含的对象类型:
Type elementType = listType.GetGenericArguments().Single();
要获取该类型的属性:
var properties = elementType.GetProperties();
推荐阅读
- python - Using Lambda to get image from S3 returns a white box in Python
- javascript - 为什么我的测试用例通过但断言实际上在 mocha 中失败
- c# - 我需要根据嵌套在对象列表中的关闭对象进行过滤
- javascript - React useEffect 和 React-Query useQuery 问题?
- go - 如何在不必实例化结构的情况下获取结构标记
- python - 这是否设置了环境变量?
- c# - 查询带有空格条件的 XML 列
- python - 如何在 Mac 上为单个项目安装不同版本的 Python
- python - 使用 GTK 后端更改 matplotlib 导航工具栏中的图标
- python - 成员上的python类操作与静态方法