开发者

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>));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜