2014-05-03 21 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); 
相關問題