返回myVar与返回(myVar)之间有区别吗?

我正在看一些C#代码的例子,并注意到一个例子包装在()的返回。

我一直都是这样做的:

return myRV; 

有没有不同的做法:

 return (myRV); 

更新:这个问题是我的博客在2010年4月12日的主题 。 感谢这个有趣的问题!

实际上,没有区别。

理论上可能有区别。 在C#规范中有三个有趣的地方可能会带来不同。

首先,将匿名函数转换为委托types和expression式树。 考虑以下:

 Func<int> F1() { return ()=>1; } Func<int> F2() { return (()=>1); } 

F1显然是合法的。 是F2吗? 从技术上讲,不。 该规范在6.5节中说,从lambdaexpression式到兼容的委托types有一个转换。 这是一个lambdaexpression式 ? 不是。这是一个包含lambdaexpression式括号 expression式

Visual C#编译器会在这里产生一个小的spec错误,并为您舍弃括号。

第二:

 int M() { return 1; } Func<int> F3() { return M; } Func<int> F4() { return (M); } 

F3是合法的。 是F4 ? 不可以。第7.5.3节规定加了括号的expression式可能不包含方法组。 再次,为了您的方便,我们违反了规范并允许转换。

第三:

 enum E { None } E F5() { return 0; } E F6() { return (0); } 

F5是合法的。 是F6吗? 不可以。该规范指出,存在从文字零到任何枚举types的转换。 “ (0) ”不是文字零,它是一个括号后跟零字母,后面跟着一个括号。 我们在这里违反了规范,实际上允许任何编译时常量expression式等于零 ,而不是只是文字零。

所以在任何情况下,我们都允许你避开它,即使技术上这样做是非法的。

存在括号可能会影响程序行为的情况下有些情况:

1。

 using System; class A { static void Foo(string x, Action<Action> y) { Console.WriteLine(1); } static void Foo(object x, Func<Func<int>, int> y) { Console.WriteLine(2); } static void Main() { Foo(null, x => x()); // Prints 1 Foo(null, x => (x())); // Prints 2 } } 

2。

 using System; class A { public A Select(Func<A, A> f) { Console.WriteLine(1); return new A(); } public A Where(Func<A, bool> f) { return new A(); } static void Main() { object x; x = from y in new A() where true select (y); // Prints 1 x = from y in new A() where true select y; // Prints nothing } } 

3。

 using System; class Program { static void Main() { Bar(x => (x).Foo(), ""); // Prints 1 Bar(x => ((x).Foo)(), ""); // Prints 2 } static void Bar(Action<C<int>> x, string y) { Console.WriteLine(1); } static void Bar(Action<C<Action>> x, object y) { Console.WriteLine(2); } } static class B { public static void Foo(this object x) { } } class C<T> { public T Foo; } 

希望你永远不会在实践中看到这一点。

不,除了句法之外没有任何区别。

回答这样的问题的一个好方法是使用Reflector并查看IL生成的内容。 通过反编译程序集,你可以学到很多关于编译器优化的知识。