简体   繁体   English

如何在C#中通过反射使用泛型创建对象

[英]How do I create an object with Generics via reflection in c#

I need to find all the instances of objects which implement interface IFOO. 我需要找到实现接口IFOO的对象的所有实例。 Then create the object and find some values of some properties of the object. 然后创建对象并找到该对象某些属性的某些值。

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);

        }
    }
}

However when the newObject is created I get the following error: 但是,当创建newObject时,出现以下错误:

Cannot create an instance of Foo`1[FooModel] because Type.ContainsGenericParameters is true 由于Type.ContainsGenericParameters为true,因此无法创建Foo`1 [FooModel]的实例

This is not what you may expect: 这不是您可能期望的:

public class Foo<FooModel> : IFoo
{
}

FooModel is not your FooModel class here but a simple type parameter. FooModel不是这里的FooModel类,而是一个简单的类型参数。 You might want to define it like this: 您可能想要这样定义它:

public class Foo<T> : IFoo where T: FooModel
{
}

However, this will not solve you problem just makes it better understandable. 但是,这不能解决您的问题,只是使其更易于理解。

Your code just finds the generic type and tries to instantiate it like this: 您的代码只是找到通用类型,并尝试像这样实例化它:

new Foo<>();

But this will not work of course because your genericArgs contains a generic type definition ( T ) instead of a constructed type ( FooModel ). 但这当然行不通,因为您的genericArgs包含通用类型定义( T )而不是构造类型( FooModel )。 Do it like this to make it work: 这样做是为了使其工作:

var makeme = type.MakeGenericType(new Type[] { typeof(FooModel) });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM