如何在c#中做“内联函数”?我想我不明白这个概念。它们像匿名方法吗?比如函数?

注意:答案几乎完全涉及内联函数的能力,即。用被调用者的主体替换函数调用站点的手册或编译器优化。如果你对匿名(又名lambda)函数感兴趣,请参阅@jalf的回答或每个人都在谈论的“lambda”是什么?


当前回答

最后,在。net 4.5中,CLR允许使用MethodImplOptions提示/suggest1方法内联。AggressiveInlining价值。它也可以在Mono的主干中使用(今天提交)。

// The full attribute usage is in mscorlib.dll,
// so should not need to include extra references
using System.Runtime.CompilerServices; 

...

[MethodImpl(MethodImplOptions.AggressiveInlining)]
void MyMethod(...)

1. 以前这里用的是“force”。我会试着解释一下这个术语。正如注释和文档中所述,如果可能的话,方法应该内联。特别是考虑到Mono(它是开放的),在考虑内联或更一般的技术(如虚函数)时,有一些特定于Mono的技术限制。总的来说,是的,这是对编译器的一个提示,但我猜这是要求的。

其他回答

你是指c++意义上的内联函数吗?其中一个正常函数的内容被自动内联复制到callsite?最终的结果是,在调用函数时实际上不会发生函数调用。

例子:

inline int Add(int left, int right) { return left + right; }

如果是,那么没有,c#中没有与之等价的东西。

或者你是指在另一个函数中声明的函数吗?如果是的话,c#通过匿名方法或lambda表达式来支持。

例子:

static void Example() {
  Func<int,int,int> add = (x,y) => x + y;
  var result = add(4,6);  // 10
}

Lambda表达式是内联函数!我认为,c#没有额外的属性,比如内联或类似的东西!

不,c#中没有这样的构造,但是. net JIT编译器可以决定在JIT时间执行内联函数调用。但我实际上不知道它是否真的在做这样的优化。 (我认为它应该:))

在某些情况下,我确实希望强制代码内联。

For example if I have a complex routine where there are a large number of decisions made within a highly iterative block and those decisions result in similar but slightly differing actions to be carried out. Consider for example, a complex (non DB driven) sort comparer where the sorting algorythm sorts the elements according to a number of different unrelated criteria such as one might do if they were sorting words according to gramatical as well as semantic criteria for a fast language recognition system. I would tend to write helper functions to handle those actions in order to maintain the readability and modularity of the source code.

我知道那些辅助函数应该是内联的,因为这是编写代码的方式,如果它永远不需要被人类理解的话。在这种情况下,我当然希望确保没有函数调用开销。

如果您的程序集将被ngen-ed,您可能想要查看TargetedPatchingOptOut。这将帮助ngen决定是否内联方法。MSDN参考

这仍然只是一个声明性的优化提示,而不是命令式命令。