How to call Func without type arguments?

Please note: my logic is a difficult task, I have simplified everything to focus on this problem.

I have a dictionary of functions that I have to call, but the function takes type T as an input argument, which is a derived type, I don't have access, and it can be anything at runtime. How to call him?

I get the following error,

Unable to cast object of type 
 'System.Func`2[DerivedClass,System.String]' to type    
 'System.Func`2[BaseClass,System.String]'.

The alternatives I tried, and I already know, I am looking for the best performance, and then the following alternatives.

  • Using dynamic
  • Recreating an expression tree and then dynamically compiling and executing

Both options are very expensive, I need a simpler approach.

It is not a question of why I get this compiler error, or I need to reverse engineer my application when I already said that I have two alternatives to calling Func, I am looking for a third simpler alternative if there is

How do I call Func<DerivedClass,String>without access to DerivedClass? I have an object with me.

class Program
{
    static void Main(string[] args)
    {

        object input = new DerivedClass();

        Func<BaseClass, string> f = null;

        Func<DerivedClass, string> a = s => s.ToString();

        object obj = a;

        // ERROR
        f = (Func<BaseClass, string>)obj;

        Console.WriteLine(f(input));

        Console.ReadLine();

    }
}


public class BaseClass {
    public override string ToString()
    {
        return "Base Class";
    }
}

public class DerivedClass : BaseClass {

    public override string ToString()
    {
        return "Derived Class";
    }

}
+4
source share
2 answers

What you are trying to do here does not really make sense. Say you have a class A and two classes B and C that inherit it.

, , Func<B, string> Func<A, string> , , C , C .

, , , Func<object, string>, , , .

+3

, . Foo:

public static void Foo(int i)
{
    Console.WriteLine(i + 2);
}

Bar. object. Foo .

public static void Bar(object o)
{
    Foo(o);
}

, . , int.

:

  • ; , ; .

  • -, , , . , , , , .

, , , (, ), :

Func<DerivedClass, string> derivedSelector = derived => derived.ToString();

Func<BaseClass, string> baseSelector = s => derivedSelector((DerivedClass)s);
+2

Source: https://habr.com/ru/post/1538452/


All Articles