我查看了一些示例C#代码,并注意到其中一个示例将返回值包装在()中。
我总是这样做:
return myRV;
这样做有区别吗:
return (myRV);
发布于 2010-04-15 01:16:33
在某些情况下,括号的存在会对程序行为产生影响:
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;
}
希望你在实践中永远不会看到这一点。
发布于 2010-02-03 02:32:47
不,除了语法上的不同,没有其他区别。
发布于 2010-02-03 04:52:40
回答这样的问题的一个好方法是使用Reflector,看看会生成什么IL。通过反编译程序集,你可以学到很多关于编译器优化之类的知识。
https://stackoverflow.com/questions/2186595
复制相似问题