1

我有这段代码:

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
    }

}

我怎样才能使我的一、二和三变量可以在课堂外读取但只在 MyClass 中设置?

MyClass obj = new MyClass();
obj.ObjectMySubClass.One = 5; //can't
int value = obj.ObjectMySubClass.One; //can do that
4

2 回答 2

1

不幸的是,我认为您不能仅使用访问修饰符来做到这一点。您可以添加其他接口只是只读属性并隐藏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
    }
}
于 2013-08-31T09:59:31.037 回答
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
于 2013-08-31T10:05:24.280 回答