在常规阵列上测试foreach box / unbox?

时间:2012-12-26 09:05:18

标签: c# .net arrays foreach boxing

我已阅读this excellent question,了解如何在int[](方框与否)循环下处理常规foreach

Array确实实现了非通用IEnumerable,因此必须在内部使用object(而不是int

但它turns out - 在运行时它实际上处理为IEnumerable<T>

如何通过简单的C#代码测试/证明(没有装箱)? (而不是阅读IL。

4 个答案:

答案 0 :(得分:3)

我喜欢@phoog的答案,所以只是为了好玩:)

助手类

public static class ILUtils
{
    private static Dictionary<short, OpCode> s_opcodes = new Dictionary<short, OpCode>();

    static ILUtils()
    {
        FieldInfo[] opCodeFields = typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static);
        foreach (FieldInfo opCodeField in opCodeFields)
        {
            if (opCodeField.FieldType != typeof(OpCode))
                continue;

            OpCode opcode = (OpCode)opCodeField.GetValue(null);
            s_opcodes.Add(opcode.Value, opcode);
        }
    }

    public static bool ContainsOpcodes(MethodInfo methodInfo, IEnumerable<OpCode> targetOpCodes)
    {
        MethodBody methodBody = methodInfo.GetMethodBody();

        using (BinaryReader ilReader = new BinaryReader(new MemoryStream(methodBody.GetILAsByteArray())))
        {
            while (ilReader.BaseStream.Position < ilReader.BaseStream.Length)
            {
                short opCodeValue = ilReader.ReadByte();
                if (opCodeValue == 0xfe)
                    opCodeValue = (short)(opCodeValue << 8 | ilReader.ReadByte());

                OpCode opCode = s_opcodes[opCodeValue];
                if (targetOpCodes.Contains(opCode))
                    return true;

                int argumentSize = 4;
                if (opCode.OperandType == OperandType.InlineNone)
                    argumentSize = 0;
                else if (opCode.OperandType == OperandType.ShortInlineBrTarget || opCode.OperandType == OperandType.ShortInlineI || opCode.OperandType == OperandType.ShortInlineVar)
                    argumentSize = 1;
                else if (opCode.OperandType == OperandType.InlineVar)
                    argumentSize = 2;
                else if (opCode.OperandType == OperandType.InlineI8 || opCode.OperandType == OperandType.InlineR)
                    argumentSize = 8;
                else if (opCode.OperandType == OperandType.InlineSwitch)
                {
                    int num = ilReader.ReadInt32();
                    argumentSize = (int)(4 * num + 4);
                }

                ilReader.BaseStream.Position += argumentSize;
            }
        }

        return false;
    }
}

使用示例

private static void BoxingForEach()
{
    IEnumerable foo = (IEnumerable)new int[10];
    foreach (int i in foo) ;
}

private static void NoBoxingForEach()
{
    int[] foo = new int[10];
    foreach (int i in foo) ;
}

static void Main(string[] args)
{
    MethodInfo boxingForEach = typeof(Program).GetMethod("BoxingForEach", BindingFlags.Static | BindingFlags.NonPublic);
    MethodInfo noBoxingForEach = typeof(Program).GetMethod("NoBoxingForEach", BindingFlags.Static | BindingFlags.NonPublic);

    Console.WriteLine("BoxingForEach is using boxing: {0}", 
        ILUtils.ContainsOpcodes(boxingForEach, new[] { OpCodes.Box, OpCodes.Unbox, OpCodes.Unbox_Any }));

    Console.WriteLine("NoBoxingForEach is using boxing: {0}", 
        ILUtils.ContainsOpcodes(noBoxingForEach, new[] { OpCodes.Box, OpCodes.Unbox, OpCodes.Unbox_Any }));
}

<强>结果

  
    

BoxingForEach正在使用拳击:True

         

NoBoxingForEach正在使用boxing:False

  

答案 1 :(得分:2)

您的问题假设不正确(链接到的问题)数组不实现通用IEnumerable<T>。他们是这样。你可以使用反射看到这个:

var array = new int[0];
var enumerator = array.GetEnumerator();
var enumeratorType = enumerator.GetType();
var propertyInfo = enumeratorType.GetProperty("Current");
var propertyType = propertyInfo.PropertyType;
Console.WriteLine(propertyType.Name); //prints "Object";
var otherEnumerator = ((IEnumerable<int>)array).GetEnumerator();
enumeratorType = otherEnumerator.GetType();
propertyInfo = enumeratorType.GetProperty("Current");
propertyType = propertyInfo.PropertyType;
Console.WriteLine(propertyType.Name); //prints "Int32";

但是,如果在静态类型数组引用上编写foreach循环,则C#编译器会将其转换为for循环。如果不看IL,我认为没有办法检查。

来自http://msdn.microsoft.com/en-us/library/system.array.aspx

重要

从.NET Framework 2.0开始,Array类实现System.Collections.Generic.IList<T>System.Collections.Generic.ICollection<T>System.Collections.Generic.IEnumerable<T>通用接口。这些实现在运行时提供给数组,因此文档构建工具不可见。因此,通用接口不会出现在Array类的声明语法中,并且没有可通过将数组转换为通用接口类型(显式接口实现)来访问的接口成员的参考主题。将数组转换为其中一个接口时要注意的关键是添加,插入或删除元素的成员会抛出NotSupportedException。

答案 2 :(得分:1)

如果没有查看发出的IL,很难验证拳击是否在幕后进行。

但试试这个:

static void Main()
{
  int[] arr1 = { 7, 9, 13, };
  Array arr2 = arr1;
  IEnumerable arr3 = arr1;  // non-generic IEnumerable

  foreach (var x in arr1)  // hold mouse over var keyword to see compile-time type
  {
    Overloaded(x);  // go to definition to see which overload is used
  }
  foreach (var x in arr2)  // hold mouse over var keyword to see compile-time type
  {
    Overloaded(x);  // go to definition to see which overload is used
  }
  foreach (var x in arr3)  // hold mouse over var keyword to see compile-time type
  {
    Overloaded(x);  // go to definition to see which overload is used
  }
}

static void Overloaded(int x)
{
  Console.WriteLine("int!");
}
static void Overloaded(object x)
{
  Console.WriteLine("object!");
}

很容易看到拳击确实发生在arr2arr3。从技术上讲,我们无法确定拳击是否与arr1发生(必须检查IL),但我们可以看到隐式类型(var)变量变为int变量,这是一种线索。

答案 3 :(得分:-1)

这样的事情令人满意吗?

        int[] foo = new int[10];

        foreach (object o in foo)
        {
            Console.WriteLine(o.GetType());
            int? bar = o as int?;
            Console.WriteLine(bar);
        }
        Console.ReadKey();

如果不检查IL是否有隐式强制转换,很难确定。