首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >return myVar和return (myVar)之间有区别吗?

return myVar和return (myVar)之间有区别吗?
EN

Stack Overflow用户
提问于 2010-02-03 02:31:02
回答 3查看 9.7K关注 0票数 88

我查看了一些示例C#代码,并注意到其中一个示例将返回值包装在()中。

我总是这样做:

代码语言:javascript
复制
return myRV;

这样做有区别吗:

代码语言:javascript
复制
return (myRV);
EN

回答 3

Stack Overflow用户

发布于 2010-04-15 01:16:33

在某些情况下,括号的存在会对程序行为产生影响:

1.

代码语言:javascript
复制
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.

代码语言:javascript
复制
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.

代码语言:javascript
复制
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;
}

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

票数 40
EN

Stack Overflow用户

发布于 2010-02-03 02:32:47

不,除了语法上的不同,没有其他区别。

票数 26
EN

Stack Overflow用户

发布于 2010-02-03 04:52:40

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2186595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档