为什么C#内联函数不带struct结构参数?

Fan*_*ius 5 .net c# optimization inline

http://blogs.msdn.com/ericgu/archive/2004/01/29/64717.aspx上,我们了解到C#不会将带有结构的方法作为形式参数进行内联.这是由于对堆栈的潜在依赖,例如递归吗?如果是这样,我可以通过将struct参数转换为这样的ref参数来获益吗?

public int Sum(int i)
{
  return array1[i] + array2[i];
}
Run Code Online (Sandbox Code Playgroud)

变成:

public int Sum(ref int i)
{
  return array1[i] + array2[i];
}
Run Code Online (Sandbox Code Playgroud)

编辑:我去尝试测试,但我无法获得任何内联.这是我尝试过的:

class Program
{
  private static string result;
  static void Main(string[] args)
  {
    Console.WriteLine(MethodBase.GetCurrentMethod().Name);
    Console.WriteLine();
    m1();
    Console.WriteLine(result);
  }
  private static void m1()
  {
    result = MethodBase.GetCurrentMethod().Name;
  }
}
Run Code Online (Sandbox Code Playgroud)

它打印"m1"作为第二行,表示它没有内联.我构建了一个Release版本并使用Ctrl-F5运行它(不附加调试器).有任何想法吗?

Meh*_*ari 5

正如乔恩所说,这是一个非常古老的帖子。我可以在以下代码中确认:

using System;
using System.Runtime.CompilerServices;

struct MyStruct
{
   public MyStruct(int p)
   {
      X = p;
   }
   public int X;

   // prevents optimization of the whole thing to a constant.
   [MethodImpl(MethodImplOptions.NoInlining)]
   static int GetSomeNumber()
   {
       return new Random().Next();
   }

   static void Main(string[] args)
   {
      MyStruct x = new MyStruct(GetSomeNumber());
      // the following line is to prevent further optimization:
      for (int i = inlinetest(x); i != 100 ; i /= 2) ; 
   }

   static int inlinetest(MyStruct x)
   {
      return x.X + 1;
   }
}
Run Code Online (Sandbox Code Playgroud)

inlinetest 方法是内联的。

主要方法拆解:

; set up the stack frame:
00000000  push        ebp
00000001  mov         ebp,esp 

; calls GetSomeNumber:
00000003  call        dword ptr ds:[005132D8h] 

; inlined function:
00000009  inc         eax  

; the dummy for loop:
0000000a  cmp         eax,64h 
0000000d  je          0000001B 
0000000f  sar         eax,1 
00000011  jns         00000016 
00000013  adc         eax,0 
00000016  cmp         eax,64h 
00000019  jne         0000000F 
0000001b  pop         ebp  
0000001c  ret 
Run Code Online (Sandbox Code Playgroud)

我已经在 Windows 7 x64 RC 上的 x86 .NET Framework 3.5 SP1 上对此进行了测试。

因为我认为使用struct参数内联方法没有本质上的错误。可能当时 JIT 还不够智能。