[英]How can I used Func<T,bool> that passed in object?
I want to create IValueConverter that getting function and object (of some kind) and return bool value. 我想创建IValueConverter来获取函数和对象(某种形式)并返回布尔值。
How can I cast function and parameters in runtime? 如何在运行时强制转换函数和参数?
public object EvaluateByValue(object MyFunc, object parameter)
{
return MyFunc(parameter);
}
For example: 例如:
Func<int,bool> MyIntFunction = i=>return i%2;int number = 8;
bool IsEvan = (bool)EvaluateByValue(MyIntFunction,8);
and another use can be: 另一个用途是:
Func<string,bool> MyStringFunction = txt=>txt=="Hello";
bool IsWelcome = (bool)EvaluateByValue(MyStringFunction,"Goodbye");
Is there any way to cast the "Func" method by the parameter type? 有什么方法可以通过参数类型强制转换“ Func”方法?
Thanks 谢谢
I would change your method to the following: 我将您的方法更改为以下内容:
public object EvaluateByValue(Delegate MyFunc, params object[] parameters)
{
return MyFunc.DynamicInvoke(parameters);
}
If the cast is your only problem, perhaps what you're looking for is: 如果演员表是您唯一的问题,也许您正在寻找的是:
var myFuncDelegate = (Func<object, bool>)parameter;
If you want the Func's parameter type to be the same as the given parameter, you would have to use reflection to cast the delegate and execute it. 如果希望Func的参数类型与给定参数相同,则必须使用反射来强制转换并执行委托。
Well the minimum amount of change would be: 好吧, 最小更改量为:
public object EvaluateByValue(Func<object, object> MyFunc, object parameter)
{
return MyFunc(parameter);
}
or to allow multiple paramaters: 或允许多个参数:
public object EvaluateByValue(Func<object[], object> MyFunc, params object[] parameter)
{
return MyFunc(parameter);
}
Although I'm not sure what you're trying to do. 尽管我不确定您要做什么。
You could do something like this for the function declaration 您可以对函数声明执行以下操作
static K EvaluateByValue<T, K>(Func<T, K> MyFunc, T parameter)
{
return MyFunc(parameter);
}
T
is the parameter type and K
is the return type T
是参数类型, K
是返回类型
So, let's say you've got this function you want to pass in 因此,假设您有要传递的功能
static string parameterFunction(string param)
{
return param + " World!";
}
you would call it like so 你会这样称呼它
var answer = EvaluateByValue<string, string>(parameterFunction, "Hello");
And answer
would be Hello World!
answer
将是“ Hello World!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.