我有这样的代码:
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
}
}
答案 0 :(得分:0)
public Three three { private set; get; }
是一个属性,Three
是Value-Type
(又名Struct
),此属性的获取返回它的副本而不是实际的引用由One
类拥有的实例。
因此,您需要创建一个新的副本,例如test.three = new Three() { Number = 5 };
,并将private set
更改为public
;
或者将Three
更改为Class
,以便通过引用使用它,并且能够通过引用get返回的实例来更改其属性。