如何通过反射创建以下内容?
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
的通用类型参数和 T2
是 System.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/