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

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


当前回答

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

其他回答

我知道这个问题是关于c#的。然而,你可以用f#在。net中编写内联函数。参见:在f#中使用' inline '

The statement "its best to leave these things alone and let the compiler do the work.." (Cody Brocious) is complete rubish. I have been programming high performance game code for 20 years, and I have yet to come across a compiler that is 'smart enough' to know which code should be inlined (functions) or not. It would be useful to have a "inline" statement in c#, truth is that the compiler just doesnt have all the information it needs to determine which function should be always inlined or not without the "inline" hint. Sure if the function is small (accessor) then it might be automatically inlined, but what if it is a few lines of code? Nonesense, the compiler has no way of knowing, you cant just leave that up to the compiler for optimized code (beyond algorithims).

没错,唯一的区别是它返回一个值。

简化(不使用表达式):

列表> < T。ForEach执行一个操作,它不期望返回结果。

所以Action<T>委托就足够了。说:

List<T>.ForEach(param => Console.WriteLine(param));

就等于说:

List<T>.ForEach(delegate(T param) { Console.WriteLine(param); });

不同之处在于参数类型和委托声明是根据用法推断的,在简单的内联方法上不需要花括号。

列表> < T。接受一个函数,期待一个结果。

因此,一个Function<T, bool>将被期望:

List<T>.Where(param => param.Value == SomeExpectedComparison);

也就是:

List<T>.Where(delegate(T param) { return param.Value == SomeExpectedComparison; });

你也可以内联声明这些方法,并将它们赋值给变量IE:

Action myAction = () => Console.WriteLine("I'm doing something Nifty!");

myAction();

or

Function<object, string> myFunction = theObject => theObject.ToString();

string myString = myFunction(someObject);

我希望这能有所帮助。

你是指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
}

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

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