繁体   English   中英

C#私有变量和Java私有变量getter和setter-区别?

[英]C# private variable & java private variable getter & setter - Difference?

我试图了解使用getters&setters和java声明的C#自动声明变量之间的区别。

在Java中,我通常这样做:

private int test;

public int getTest() {
    return test;
}

public void setTest(int test) {
    this.test = test;
}

但是在C#中,我尝试了如下操作:

private int test { public get; public set};

但这根本不允许访问该变量。 所以我最终得到了这个:

public int test { get; set; }

这样一来,我可以从类外部访问变量测试。

我的问题是,两者之间有什么区别? C#实现将变量公开是一个坏主意吗?

在C#中,我已将该变量声明为“ public”。 而在Java中,它被声明为“私有”。 这会产生影响吗?

找到一个很好的答案(除了低于) 这里

完全一样。

无论如何,您在C#中定义的自动属性将编译为getter和setter方法。 它们被分类为“语法糖”。

这个:

public int Test { get; set; }

..编译为此:

private int <>k____BackingFieldWithRandomName;

public int get_Test() {
    return <>k____BackingFieldWithRandomName;
}

public void set_Test(int value) {
    <>k____BackingFieldWithRandomName = value;
}

在第一个示例中,您有一个支持字段。

C#您可以执行以下操作:

private int test { get; set; };

或公开property (完全有效)

public int test { get; set; };

您还可以在C#具有支持字段,这些字段在以该语言引入Properties之前更为常见。

例如:

private int _number = 0; 

public int test 
{ 
    get { return _number; }
    set { _number = value; }
}

在上面的示例中, test是访问private field的公共Property

这是C#编译器提供的解决方案,可轻松创建getter和setter方法。

private int test;

public int Test{
   public get{
      return this.test;
   }
   public set{
      this.test = value;
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM