已经有一个类似的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/