C# 通过反射实例化编译已知类型的类型化IEnumerable
仅使用.net 3.5,我有示例类:C# 通过反射实例化编译已知类型的类型化IEnumerable,c#,generics,reflection,C#,Generics,Reflection,仅使用.net 3.5,我有示例类: public class Table1 { public IEnumerable<Table2> Items { get; set; } } 我想你只是错过了一个简单的演员阵容: 而不是: table1.Items = instance; 让它: table1.Items = instance as IEnumerable<Table2>; table1.Items=实例为IEnumerable; 如果你知道你想要一个列表
public class Table1
{
public IEnumerable<Table2> Items { get; set; }
}
我想你只是错过了一个简单的演员阵容: 而不是:
table1.Items = instance;
让它:
table1.Items = instance as IEnumerable<Table2>;
table1.Items=实例为IEnumerable;
如果你知道你想要一个列表,为什么不能直接使用新列表()
?通常,只有在运行时才知道类型时才使用Activator.CreateInstance
,通常使用基于字符串的配置值
不过,您只需将instance
显式转换为IEnumerable
或List
,其中一个应该可以工作:
table1.Items = (IEnumerable<Table2>) instance;
table1.Items=(IEnumerable)实例;
“我不能将其转换为所需类型”-为什么不能?Austin Salonen,请参阅editI不能使用任何直接转换,因为它需要参考表2,我不能使用该表。那么,您可以将表1
中项的声明更改为对象吗?我不能使用任何直接转换,因为它需要参考表2,但我不能harcode@devi您在代码中有一个对表2的引用:var gt=t.MakeGenericType(typeof(Table2))代码>这只是一个示例,在我的代码中,我使用GetType()而不是typeof()和未引用的类型
table1.Items = instance as IEnumerable<Table2>;
table1.Items = (IEnumerable<Table2>) instance;