如何使用 Reflection 设置类型为 List的属性
已经有一个类似的问题但似乎并没有询问问题所暗示的情况。
用户询问列表中的自定义类,但他的列表对象是字符串类型。
我有一个类 Foo,它有一个 Bars 列表:
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 获得的,Bar 是同一程序集中的公共类。我需要以某种方式了解这种类型。我似乎看不出 Foo 中包含的列表的类型是什么。但我知道这是一个清单。我看到列表属性为 List`1。
我需要查看列表包含什么类型的对象并相应地处理它。
There is already a similar question but it didn't seem to ask about the situation that the question implies.
The user asked about custom classes in a list but his list object is of type string.
I have a class Foo that has a list of Bars:
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(){}
}
I instantiate Foo using reflection via Activator.CreateInstance(). Now I need to populate that list of bars with Bar objects.
Foo is obtained using
Assembly.GetAssembly(FooBase).GetTypes().Where(type => type.IsSubclassOf(FooBase));
Bar is a public class in the same Assembly. I'll need to get at that type somehow. I can't seem to see what the type of the list contained in Foo is. I know it's a list though. I'm seeing the list property as List`1.
I'd need to see what type of object the list holds and handle that accordingly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
文本
是泛型在引擎盖下的编写方式 - 意思是“具有 1 个泛型类型 arg 的列表,又名
List<>
”。如果您有PropertyInfo
,则应该已设置;这将是封闭的通用List
。您是否想在给定只是这个的情况下找到Bar
?如果是这样,这会在各种问题中讨论,包括这个;复制密钥位(我更喜欢针对
IList
进行编码,因为它处理一些边缘情况,例如从List< 继承 /代码>):
The text
is the way that generics are written under the bonnet - meaning "List with 1 generic type arg, aka
List<>
". If you have aPropertyInfo
, you should be set; this will be the closed genericList<Bar>
. Is it that you want to find theBar
given just this?If so, this is discussed in various questions, including this one; to duplicate the key bit (I prefer to code against
IList<T>
, since it handles a few edge-cases such as inheriting fromList<T>
):