是否可以使用不带Reflection.Emit的反射将Func <object,object =“”>强制转换为Func <t1,tresult =“”>

时间:2018-07-02 18:32:16

标签: c# .net reflection

我正在尝试创建将与AOT(特别是Unity3d和IL2CPP)一起使用的Autofac样式的自动委托工厂的实现。

我遇到的主要问题是无法在运行时从Func<object, object>投射到Func<T1, TResult>

有什么方法可以通过反射来做到这一点,但是避免在运行时生成IL代码(即,不使用Reflection.Emit)?

Func<object, object> func = delegate (object arg1)
{
    return arg1.ToString() + " bar";
};

Func<string, string> func2;
func2 = (Func<string, string>)func;


Console.WriteLine(func2("foo")); // "foo bar" ? :(
// System.InvalidCastException: Unable to cast object of type 'System.Func`2[System.Object,System.Object]' to type 'System.Func`2[System.String,System.String]'.

1 个答案:

答案 0 :(得分:2)

我认为不可能将一种类型的Func转换为另一种类型的Func。视使用情况而定,您可以将其中一种包装起来以达到所需的结果,如下所示。

Func<object, object> func = delegate (object arg1)
{
    return arg1.ToString() + " bar";
};

// Wrap func with a call by func2 to get the desired casting.
Func<string, string> func2 = o => func(o) as string;

Console.WriteLine(func2("foo"));