首页 文章

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

提问于
浏览
0

我试图理解C#auto变量与getter和setter以及java声明之间的区别 .

在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中它被声明为“私有” . 这有什么影响吗?

Found a really good answer (in addition to those below) here

3 回答

  • 1

    它完全一样 .

    无论如何,您在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;
    }
    
  • 3

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

    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 .

  • 0

    这是解决方案,它由C#编译器提供,可以快速创建getter和setter方法 .

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

相关问题