如何将类实例的变量设置为只读外部类,但其成员是否可读/写?

时间:2016-07-16 12:49:04

标签: c#

我有这样的代码:

struct Three
{
  public int Number;
}

class One
{
  public Three three;
  public One(){three = new Three();}
}

class Two
{
  private One test = new One();

  public void SomeFunction()
  {

    test.three.Number = 5; // This works fine
  }
}

但是我只需要允许类One能够直接写入三个变量(做这样的东西三个= new Three()),所以第二类不能这样做:test.three = new Three( );但它应该可以做这个test.three.Number = 5; (如在该结构的那个实例中的更改值)所以我这样做了:

struct Three
{
  public int Number;
}

class One
{
  public Three three {private set; get;}
  public One(){three = new Three();}
}

class Two
{
  private One test = new One();

  public void SomeFunction()
  {

    test.three.Number = 5; // This says i can't modify the return value because it is not a variable
  }
}

1 个答案:

答案 0 :(得分:0)

public Three three { private set; get; }是一个属性,ThreeValue-Type(又名Struct),此属性的获取返回它的副本而不是实际的引用由One类拥有的实例。

因此,您需要创建一个新的副本,例如test.three = new Three() { Number = 5 };,并将private set更改为public;

或者将Three更改为Class,以便通过引用使用它,并且能够通过引用get返回的实例来更改其属性。