[英]Instantiate a reflected delegate type
我有一个类型变量
using System;
using System.Linq;
using System.Reflection;
...
var validateFuncType = typeof(Func<,>).MakeGenericType(someVariableType, typeof(bool));
现在,我检查someVariableType
遵循约定,
var validateOfType = someVariableType
.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.SingleOrDefault(mi =>
{
if (mi.Name != "Validate" || mi.ReturnType != typeof(bool))
{
return false;
}
var parameters = mi.GetParameters();
return parameters.Length == 0;
});
然后根据支票
object validateFunc;
if (validateOfType == null)
{
validateFunc = // some noop func that returns true.
// e.g. _ => true;
}
else
{
validateFunc = // a delegate that calls the conventional validate
// e.g. someVariable => someVariable.Validate();
}
实例化委托类型的实例。
您能帮我做到吗,如何实例化validateFuncType
,它调用常规实现(如果存在)?
如果我理解正确,那么您正在寻找Delegate.CreateDelegate
:
var alwaysReturnTrueMethodInfo = typeof(YourClass).GetMethod("AlwaysReturnTrue").MakeGenericMethod(someVariableType);
Delegate validateFunc;
if (validateOfType == null)
{
validateFunc = Delegate.CreateDelegate(validateFuncType, alwaysReturnTrueMethodInfo);
}
else
{
validateFunc = Delegate.CreateDelegate(validateFuncType, validateOfType);
}
其中AlwaysReturnTrue
是这样声明的辅助静态方法:
public static bool AlwaysReturnTrue<T>(T t) { return true }
您可以通过以下方式之一进行:
// create an object of the type
var obj = Activator.CreateInstance(validateFuncType);
然后,您将在obj中获得validateFuncType的实例。
另一种方法是使用反射:
// get public constructors
var ctors = validateFuncType.GetConstructors(BindingFlags.Public);
// invoke the first public constructor with no parameters.
var obj = ctors[0].Invoke(new object[] { });
这是从此SO答案中获取的 。 因此,该问题(和答案)可能被标记为重复。
在注意到Func<>
输入参数是不变的之后,我做了什么。
object validateFunc = validateOfType != null
? config => (bool)validateOfType.Invoke(config, new object[0])
: new Func<object, bool>(_ => true);
我不确定这是否比@Sweeper的答案更好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.