如何使用反射来设置属性与类型列表与LT的; CustomClass> [英] How do I use Reflection to set a Property with a type of List<CustomClass>
问题描述
有已经是一个类似问题,但它似乎没有询问的问题暗示的情况。
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.
我有了酒吧列表的类Foo:
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(){}
}
我实例化美孚使用反射通过Activator.CreateInstance()。现在,我需要填充的酒吧对象条该列表。
I instantiate Foo using reflection via Activator.CreateInstance(). Now I need to populate that list of bars with Bar objects.
使用获得的美孚
Assembly.GetAssembly(FooBase).GetTypes().Where(type => type.IsSubclassOf(FooBase));
酒吧是在同议会一个公共类。我需要在该类型得到莫名其妙。我似乎无法看到包含在富列表的类型。我知道这是一个名单,但。我看到名单财产List`1。
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.
推荐答案
文本
List`1
是泛型是引擎盖下编写方式 - 意思是1泛型类型ARG名单,又名列表与LT;>
。如果你有一个的PropertyInfo
,您应该设置;这将是封闭的通用列表<酒吧GT;
。难道你想找到酒吧
给出的只是吗?
is the way that generics are written under the bonnet - meaning "List with 1 generic type arg, aka List<>
". If you have a PropertyInfo
, you should be set; this will be the closed generic List<Bar>
. Is it that you want to find the Bar
given just this?
如果这样,这是在不同的问题,包括这个讨论;重复键位(我更喜欢代码对的IList< T>
,因为它处理了一些边缘的情况下,如的继承的列表< T>
):
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 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;
}
这篇关于如何使用反射来设置属性与类型列表与LT的; CustomClass>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!