2014-05-03 25 views
0

下面的源工程,并使用.NET在Visual Studio中,当如预期,但它使用单声道框架时抛出上述异常:的ArgumentException:方法的返回类型是不兼容的(单声道)

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:/

例外

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() 
... 
+0

我不确定这个建议有多可靠,但它似乎*工作(http://hastebin.com/ahoxoleyed.cs)。任何想法? –

回答

1

好吧,我不完全理解下面的,但它似乎为工作无论是.NET还是Mono,它都不分配。任何意见的警告或可靠性将不胜感激!

这被改编from here(唯一的区别是,Expression.Parameter需要的第二参数取悦其用于通过统一的单声道的版本

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); 
相关问题