gpt4 book ai didi

c# - 为什么以下两种方法生成相同的 IL?

转载 作者:行者123 更新时间:2023-11-30 15:43:59 24 4
gpt4 key购买 nike

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

}
}

如果您看到为这两种方法生成的 IL,它们看起来相同,或者我遗漏了什么...为什么对第一个 Include 方法进行装箱?

最佳答案

ValueType 是一个引用类型。诚实的。当它是 T 时,它只是一个结构。您需要将所有 ValueType 替换为 T 以使其不装箱。但是,不会有从 Tint 的内置转换...所以:你不能。你将不得不装箱。此外,并非所有枚举都是基于 int 的(例如,对于 enum Foo : ushort,您的 box-as-enum、unbox-as-int 将失败)。

在 C# 4.0 中,dynamic 可能是一种厚颜无耻的方式:

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

否则,一些元编程(本质上是做 dynamic 做的,但是是手动的):

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

关于c# - 为什么以下两种方法生成相同的 IL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6410528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com