我有这段代码:
class MyClass
{
public class MySubClass
{
public int One { private set; public get; }
public int Two { private set; public get; }
public int Three { private set; public get; }
};
public MySubClass ObjectMySubClass { private set; public get; }
private void SetSomething()
{
ObjectMySubClass.One = 5; //can do that
}
}
如何才能使我的One,Two和Three变量可以在课外读取,但只在MyClass中设置?
MyClass obj = new MyClass();
obj.ObjectMySubClass.One = 5; //can't
int value = obj.ObjectMySubClass.One; //can do that
答案 0 :(得分:1)
不幸的是,我不认为你只能使用访问修饰符来做到这一点。您可以添加其他界面只是readonly属性并隐藏MySubClass
为私有:
class MyClass
{
public interface IMySubClass
{
int One { get; }
int Two { get; }
int Three { get; }
}
private class MySubClass : IMySubClass
{
public int One { set; get; }
public int Two { set; get; }
public int Three { set; get; }
};
private MySubClass _objectMySubClass;
public IMySubClass ObjectMySubClass
{
get { return _objectMySubClass; }
}
private void SetSomething()
{
_objectMySubClass.One = 5; //can do that
}
}
答案 1 :(得分:0)
一种方法是使用构造函数:
class MyClass
{
public class MySubClass
{
public int One { private set; get; }
public int Two { private set; get; }
public int Three { private set; get; }
public MySubClass(int one, int two, int three)
{
this.One = one;
this.Two = two;
this.Three = three;
}
};
public MySubClass ObjectMySubClass { private set; get; }
private void SetSomething()
{
this.ObjectMySubClass = new MySubClass(1, 2, 3);
}
}
然后:
MyClass obj = new MyClass();
//obj.ObjectMySubClass.One = 5; //can't
//obj.ObjectMySubClass = new MyClass.MySubClass(1, 2, 3); //can't
int value = obj.ObjectMySubClass.One; //can do that