ArgumentException:方法返回类型不兼容(Mono)

时间:2014-05-03 17:28:34

标签: c# exception delegates mono argumentexception

在Visual Studio中使用.NET时,以下源代码按预期工作,但在使用Mono框架时抛出上述异常:

class Foo<TEnum> where TEnum : struct {

    private static Func<int, int> Identity = (value) => value;
    private static Func<int, TEnum> IntToEnum = Delegate.CreateDelegate(typeof(Func<int, TEnum>), Identity.Method) as Func<int, TEnum>;
    private static Func<TEnum, int> EnumToInt = Delegate.CreateDelegate(typeof(Func<TEnum, int>), Identity.Method) as Func<TEnum, int>;

    public static bool EnumEquals(TEnum lhs, TEnum rhs) {
        return EnumToInt(lhs) == EnumToInt(rhs);
    }

}

Foo<SomeEnum>.EnumEquals(SomeEnum.A, SomeEnum.B);

是否有解决方法,如上所述,避免装箱/取消装箱值?

我坚持使用Unity内部的Mono实现:/

例外

ArgumentException: method return type is incompatible
System.Delegate.CreateDelegate (System.Type type, System.Object firstArgument, System.Reflection.MethodInfo method, Boolean throwOnBindFailure) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System/Delegate.cs:190)
System.Delegate.CreateDelegate (System.Type type, System.Reflection.MethodInfo method, Boolean throwOnBindFailure) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System/Delegate.cs:291)
System.Delegate.CreateDelegate (System.Type type, System.Reflection.MethodInfo method) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System/Delegate.cs:295)
Foo`1[SomeEnum]..cctor ()
...

1 个答案:

答案 0 :(得分:1)

好吧,我并不完全理解以下内容,但似乎适用于.NET和Mono并且它没有分配。任何关于警告或可靠性的评论都将不胜感激!

这已经改编from here(唯一的区别是Expression.Parameter需要第二个参数来取悦Unity使用的Mono版本。

internal static class CastTo<T> {
    public static T From<S>(S s) {
        return Cache<S>.caster(s);
    }

    static class Cache<S> {
        internal static readonly Func<S, T> caster = Get();

        static Func<S, T> Get() {
            var p = Expression.Parameter(typeof(S), "S");
            var c = Expression.ConvertChecked(p, typeof(T));
            return Expression.Lambda<Func<S, T>>(c, p).Compile();
        }
    }
}

然后可以按如下方式使用:

public enum Example {
    A,
    B,
    C,
}

long example = CastTo<long>.From<Example>(Example.B);