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;
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";
}
}