简体   繁体   中英

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.

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?

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.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM