【问题标题】:ArgumentException: method return type is incompatible (Mono)ArgumentException:方法返回类型不兼容(单声道)
【发布时间】:2014-05-03 17:28:34
【问题描述】:

以下源代码在 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 ()
...

【问题讨论】:

标签: c# exception delegates mono argumentexception


【解决方案1】:

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

这是改编 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);

【讨论】:

    猜你喜欢
    • 2016-02-01
    • 1970-01-01
    • 2012-05-08
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 2011-07-13
    • 2014-08-29
    相关资源
    最近更新 更多