[英]How do I create an object with Generics via reflection in c#
我需要找到實現接口IFOO的對象的所有實例。 然后創建對象並找到該對象某些屬性的某些值。
public interface IFoo
{
}
public class FooModel
{
public string Code { get; set; }
}
public class Foo<FooModel> : IFoo
{
}
public class Create{
public void CreateInstances()
{
var itype = typeof(IFoo);
var types = (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
from assemblyType in domainAssembly.GetTypes()
where itype.IsAssignableFrom(assemblyType)
select assemblyType).Where(m => m != itype);
foreach (var type in types)
{
var genericArgs = type.GetGenericArguments();
var makeme = type.MakeGenericType(genericArgs);
var newObject = Activator.CreateInstance(makeme);
}
}
}
但是,當創建newObject時,出現以下錯誤:
由於Type.ContainsGenericParameters為true,因此無法創建Foo`1 [FooModel]的實例
這不是您可能期望的:
public class Foo<FooModel> : IFoo
{
}
FooModel
不是這里的FooModel
類,而是一個簡單的類型參數。 您可能想要這樣定義它:
public class Foo<T> : IFoo where T: FooModel
{
}
但是,這不能解決您的問題,只是使其更易於理解。
您的代碼只是找到通用類型,並嘗試像這樣實例化它:
new Foo<>();
但這當然行不通,因為您的genericArgs
包含通用類型定義( T
)而不是構造類型( FooModel
)。 這樣做是為了使其工作:
var makeme = type.MakeGenericType(new Type[] { typeof(FooModel) });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.