使用泛型接口作为带反射的参数调用泛型方法会导致ArgumentException

时间:2015-01-30 13:12:21

标签: c# generics expression

假设我有以下界面:

public interface IInterface<out T> {
    T Instance { get; set; }
}

和类中的方法:

public void DoSomething<T>(IInterface<T> @object) { ... }

现在我想用DoSomething类型的对象调用IInterface<Foo>,并在此类中使用Expression。

所以我在同一个类中有一个方法:

public void FooBar() {
    object methodGeneric = ...;
    Type genericType = methodGeneric.GetType(); // of type Foo

    object o = ...;
    Type t = o.GetType(); // of type IInterface<Foo>
    MethodInfo m = GetType().GetMethod("DoSomething").MakeGenericMethod(genericType));

    var param = Expression.Parameter(t, "o");
    var cast = Expression.Convert(param, typeof(object));
    var @this = Expression.Constant(this);
    var call = Expression.Call(@this, m, cast); // here's where the exception occurs.
    var lambda = Expression.Lambda<Action<object>>(call, param).Compile();
    lambda(o);
}

然后发生的异常如下:

Expression of type 'System.Object' cannot be used for parameter of type 'IInterface' of method 'void DoSomething[Foo](IInterface[Foo])'

我尝试使用Expression.TypeAs而不是使用相同的异常转换。

有人有任何想法吗?

0 个答案:

没有答案
相关问题