在我的课程中我有以下属性:
public List<ClassP> MyPlanes { get; set; }
另一种方法中,我有一个上面属性的propertyInfo
(函数本身不知道propertyinfo来自哪里)。现在我正在尝试在只有MyPlanes
的propertyInfo
的情况下创建classP列表
。到目前为止,我的尝试似乎都是徒劳的,这是我到目前为止所做的:
变量prop是MyPlanes的PropertyInfo。
public void GenerateList(PropertyInfo prop)
{
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericArguments().Length > 0)
{
List<prop.PropertyType.GetGenericArguments().First()> myValueList =
new List<prop.PropertyType.GetGenericArguments().First()>();
}
}
使用上面的代码创建列表会出现以下错误:
使用通用类型“System.Collections.Generic.List<T>”需要1个类型参数
非常感谢您的帮助。注意:我想以可见的语法(或类似的语法)创建列表。我希望尽可能地使我的代码通用。
prop.PropertyType.GetGenericArguments()
只一次,并缓存结果。我相信这是一个耗费资源的操作。 - Matt Burland