关于最佳实践的 C# 神话?

标签 c# .net .net-2.0 c#-2.0

我的同事不断告诉我评论中列出的事情。

我很困惑。 有人可以为我揭开这些东西的神秘面纱吗?

class Bar
{
    private int _a;

    public int A
    {
        get { return _a; }
        set { _a = value; }
    }

    private Foo _objfoo;

    public Foo OFoo
    {
        get { return _objfoo; }
        set { _objfoo = value; }
    }

    public Bar(int a, Foo foo)
    {
        // this is a bad idea
        A = a;
        OFoo = foo;
    }

    // MYTHS
    private void Method()
    {
        this.A    //1 -
        this._a   //2 - use this when inside the class e.g. if(this._a == 2)
        A         //3 - use this outside the class e.g. barObj.A
        _a        //4 - 
                  // Not using this.xxx creates threading issues.
    }
}
class Foo
{
    // implementation
}

最佳答案

如果没有名称冲突,this. 是多余的。仅当您需要对当前对象的引用或者您有一个与字段同名的参数时才需要它。

线程问题与它无关。混淆可能来自这样一个事实,即大多数静态成员的实现是线程安全的,并且静态成员不能(!)用 this. 调用,因为它们没有绑定(bind)到实例。

关于关于最佳实践的 C# 神话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2621523/

相关文章:

c# - Lambda 语法 : elements where a function has a certain value over a range of arguments

c# - 具有 AutoScroll 性能的虚拟化 ListView(慢)

c# - 读取麦克风分贝和音调/频率

c# - ViewBag RuntimeBinderException(MVC 4、ASPX)

c# - 你如何找到锁的所有者(Monitor)?

c# - 需要帮助从 C# 中的 HTML 页面中提取标签

.net - 如何使用 Web API 2 + AspNet Identity 2 扩展 IdentityRole

c# - 从 .NET 2.0 向下迁移到 .NET 1.1 - DllImport 不再有效

c# - 获取当前类的名称

iis - 具有不同 .net 框架的虚拟目录