C# 实例化反射的委托类型

C# 实例化反射的委托类型,c#,lambda,reflection,C#,Lambda,Reflection,我有一个类型变量 using System; using System.Linq; using System.Reflection; ... var validateFuncType = typeof(Func<,>).MakeGenericType(someVariableType, typeof(bool)); 那就看支票了 object validateFunc; if (validateOfType == null) { validateFunc = // so

我有一个类型变量

using System;
using System.Linq;
using System.Reflection;

...

var validateFuncType = typeof(Func<,>).MakeGenericType(someVariableType, typeof(bool));
那就看支票了

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

// 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[] { });

这是从一个地方拿走的。因为这个问题(和答案)可能被标记为重复。

如果我理解正确,您正在寻找:

其中,
AlwaysReturnTrue
是一个助手静态方法,声明如下:

public static bool AlwaysReturnTrue<T>(T t) { return true }
public static bool AlwaysReturnTrue(T){return true}

注意到
Func
的输入参数是反变的,然后我做了什么

object validateFunc = validateOfType != null
                ? config => (bool)validateOfType.Invoke(config, new object[0])
                : new Func<object, bool>(_ => true);
objectvalidatefunc=validateOfType!=无效的
? config=>(bool)validateOfType.Invoke(配置,新对象[0])
:new Func(=>true);

我不确定这是否比

好,但我如何才能使一个
\u=>正确和另一个执行
t=>t.Validate()?您的问题是:“如何实例化validateFuncType”?我就是这么回答的。如果您希望实例化类型的特定(接口)方法,则需要将其转换为更特定的类型,然后转换为“just”对象。对于具有Validate方法和返回类型的类型,是否存在公共接口或基类!=布尔?将创建的对象强制转换为接口或基类。我澄清了这个问题。顺便说一句:我发现防止使用var/始终使用显式类型是一个很好的做法。为了便于阅读。对于有关
var
的长期争论,您可以从这里开始,在委托类型与代码的其余部分匹配之前,这永远不会起作用。它寻找一个没有参数的方法,所以它需要是
Func
,而不是
Func
。或者更简单,只要
typeof(Func)
。考虑接受其中一个答案,如果这些答案不满足您的要求,请留在循环中并指出您仍然缺少的内容。您理解正确,我制作了一个
bool CallByConventionValidate(dynamic target){return target.Validate();}
这看起来很糟糕,但也很有效。它很有用,我从中学到了一些好东西,但在注意到
Func
的输入参数是反变的之后,我做到了。我仍然不确定最好的答案是什么。
public static bool AlwaysReturnTrue<T>(T t) { return true }
object validateFunc = validateOfType != null
                ? config => (bool)validateOfType.Invoke(config, new object[0])
                : new Func<object, bool>(_ => true);