简体   繁体   中英

Why the following two methods generating the same IL?

 public static class Extensions
{
    public static T Include<T>(this System.Enum type,T value) where T:struct 
    {
      return ((T) (ValueType) (((int) (ValueType) type | (int) (ValueType) value)));

    }
    public static T Include1<T>(this System.Enum type, T value) 
    {
        return ((T)(object)((int)(object)type | (int)(object)value));

    }
}

If you see the IL generated for these two methods they look the same or am i missing something... why boxing is happening for the first Include method?

ValueType is a reference-type. Honest. It is only a struct when it is T . You would need to replace all the ValueType with T for it not to box. However, there will be no inbuilt cast from T to int ... so: you can't. You will have to box. Plus, not all enums are int -based (your box-as-enum, unbox-as-int will fail for a enum Foo : ushort , for example).

In C# 4.0, dynamic might be a cheeky way to do this:

public static T Include<T>(this T type, T value) where T : struct
{
    return ((dynamic)type) | value;
}

Otherwise, some meta-programming (essentially to do what dynamic does, but manually):

static void Main()
{
    var both = Test.A.Include(Test.B);
}
enum Test : ulong
{
    A = 1, B = 2
}

public static T Include<T>(this T type, T value) where T : struct
{
    return DynamicCache<T>.or(type, value);
}
static class DynamicCache<T>
{
    public static readonly Func<T, T, T> or;
    static DynamicCache()
    {
        if(!typeof(T).IsEnum) throw new InvalidOperationException(typeof(T).Name + " is not an enum");
        var dm = new DynamicMethod(typeof(T).Name + "_or", typeof(T), new Type[] { typeof(T), typeof(T) }, typeof(T),true);
        var il = dm.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Or);
        il.Emit(OpCodes.Ret);
        or = (Func<T, T, T>)dm.CreateDelegate(typeof(Func<T, T, T>));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM