我的同事不断告诉我评论中列出的事情。
我很困惑。 有人可以为我揭开这些东西的神秘面纱吗?
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/