C#反思:如何使用"对象"作为"类型参数"

age*_*t47 1 c# generics reflection constructor type-parameter

我有这个域名:

public class GenClass<T> { }

public class Type1 { }

public class Type2 { }

public class GenType1 : GenClass<Type1> { }

public class GenType2 : GenClass<Type1> { }

public class GenType3 : GenClass<Type2> { }

public class GenType4 : GenClass<string> { } 

public class GenType5 : GenClass<int> { } 
Run Code Online (Sandbox Code Playgroud)

这个逻辑:

public class SomeClass {
    public void Add<T>(GenClass<T> t) { }
}
Run Code Online (Sandbox Code Playgroud)

而这个消费者:

public class Consumer {
    public void Method() {
        var some = new SomeClass();
        some.Add(new GenType1());
        some.Add(new GenType2());
        some.Add(new GenType3());
        some.Add(new GenType4());
        some.Add(new GenType5());
    }
}
Run Code Online (Sandbox Code Playgroud)

但是不是GenType(n)单独添加每个,而是创建一个这样的方法:

public void AddFromAssembly<TAssembly>(SomeClass some, Type baseType) {
    var list = typeof(TAssembly).Assembly.GetTypes()
        .Where(t => baseType.IsAssignableFrom(t)
            && !baseType.Equals(t))
        .ToList();
    list.ForEach(type => {
        var ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null,
                                       Type.EmptyTypes, null);
        var obj = ctor.Invoke(new object[] { });
        some.Add(obj); //????
    });
}
Run Code Online (Sandbox Code Playgroud)

并希望像这样称呼它:

public class Consumer {
    public void Method() {
        var some = new SomeClass();
        AddFromAssembly<GenType1>(some, typeof(GenClass<>));
    }
}
Run Code Online (Sandbox Code Playgroud)

但是some.Add方法是一种通用的方法和ctor.Invoke方法返回一个object.你有什么想法解决这个问题吗?提前致谢.

更新问题不完整,我解决了.感谢您的评论.

usr*_*usr 7

要么这样做:

Add<object>(obj); //this will work with T typed as object
Run Code Online (Sandbox Code Playgroud)

要么:

typeof(Some).GetMethod("Add").MakeGenericMethod(new [] { typeof(obj.GetType()).Invoke(some, new [] { obj });
Run Code Online (Sandbox Code Playgroud)

反射版本将在运行时使用T的确切类型obj.