c# - 如何调用 Activator.CreateInstance,将方法作为构造函数参数传递?

标签 c# reflection system.reflection

如何通过反射创建以下内容?

var t = new SomeFrameworkType<string, string>(s => MyClass.MyMethod(s));

这是我目前所拥有的:

var typeParamOne = Type.GetType("System.String");
var typeParamTwo = Type.GetType("System.String");
var myClass= Type.GetType("ConsoleApplication.MyClass");
var myMethod = myClass.GetMethod("MyMethod");
var type = typeof(SomeFrameworkType<,>);
var typeArgs = new[] {typeParamOne, typeParamTwo };
var constructed= type.MakeGenericType(typeArgs);
var instance = Activator.CreateInstance(constructed, myMethod);

样本是这样的,因为大部分所需信息将未知,并将作为参数提供。

现在,“实例”分配将抛出异常。我怎样才能适本地传递给构造函数?

此外,我如何将结果转换为 SomeFramework,以便在我不知道类型参数时使用它?

谢谢!

最佳答案

假设SomeFrameworkType<,>定义类似于以下内容:

class SomeFrameworkType<T1, T2> { 
  public SomeFrameworkType(Func<T1, T2> func) {}
}

T1 的通用类型参数和 T2System.String (就像在 OP 的示例中),然后它可以使用以下代码通过反射实例化:

var typeParamOne = typeof (string);
var typeParamTwo = typeof(string);
var myClass = typeof(ConsoleApplication.MyClass);
var myMethod = myClass.GetMethod("MyMethod");
var type = typeof(SomeFrameworkType<,>);
var typeArgs = new[] { typeParamOne, typeParamTwo };
var constructed = type.MakeGenericType(typeArgs);

// construct the delegate
var ctrArgs = typeof(Func<,>).MakeGenericType(typeArgs);
var dlgate = Delegate.CreateDelegate(ctrArgs, myMethod);

var instance = Activator.CreateInstance(constructed, dlgate);

AFAIK,我们至少需要知道用于转换结果 object 的泛型类型参数至 SomeFrameworkType<,>或者(正如 Jon G 所指出的那样)使用 SomeFrameworkType<,> 的非泛型基类型如果有的话。

var casted = instance as SomeFrameworkType<string, string>;

关于c# - 如何调用 Activator.CreateInstance,将方法作为构造函数参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20952205/

相关文章:

c# - Type.GetType() 和 Type.GetElementType() 之间的基本区别是什么

c# - 为什么 CanRead 和 CanWrite 在 C# 中为具有覆盖访问器的属性返回 false?

c# - 如何动态加载 XAML 以获取控件信息

c# - 如何将 Class<Derived> 转换为 Class<Base>?

c# - 具有 services.AddIdentity 的 WebApi 授权属性返回 404 Not Found

java - 动态地将Object实例转换为真正的子类实例

java - 如何在运行时调用方法时忽略修饰符 - JAVA

C# 托管内存泄漏

C# - 为什么我不能创建通用接口(interface)类型的 IEnumerable?

c++ - 使用 GCC 编译没有 RTTI 的时间 typeid