具有可变对象的自动属性

Auto-properties with mutable objects

提问人:nostro 提问时间:8/30/2016 最后编辑:Blorgbeardnostro 更新时间:8/30/2016 访问量:141

问:

我正在尝试为可变对象创建属性。这是自动属性的问题吗?例如,以下代码将允许对可变对象进行不必要的操作。我该如何避免这种情况?

public class Mutable{
    public int Value { get; set; }
}

public class ClassWithMutable{
    public Mutable Object { get; }

    public ClassWithMutable(){
        this.mutable = new Mutable();
        this.mutable.Value = 0;
    }
}

public class Demo{
    public static void Main(String[] args){
        ClassWithMutable test = new ClassWithMutable();
        Mutable o = test.Object;
        o.Value = 1;
    }
}
c# 可变 自动属性

评论

1赞 Quantic 8/30/2016
所以你不想让工作?o.Value = 1;
3赞 Glorin Oakenfoot 8/30/2016
使您的对象不可变?如果你定义了一个 setter,那么你就可以接受可变性。
0赞 nostro 8/30/2016
我希望我的 Mutable 对象仅在 ClassWithMutable 类中可变
1赞 Roman Marusyk 8/30/2016
然后在 ClassWithMutable 中将其设为私有

答:

1赞 Cameron 8/30/2016 #1

我试图理解你问题的意图,而不是你的问题,我说得有点短。但是,我想我想出了一些东西。

您可以在只读界面下“屏蔽”可变对象。

public class ClassWithMutable
{
    public IImumutable Mutable { get { return _mutable; } }
    private Mutable _mutable;
    public ClassWithMutable()
    {
        _mutable = new Mutable()
        {
            Value = 1
        };
    }
}
public interface IImumutable
{
    int Value { get; }
}
public class Mutable : IImumutable
{
    public int Value { get; set; }
}

只要您的实例将实例公开为实例,那么使用者就无法轻松更改它。(我很容易强调,因为几乎总有一种方法可以改变它。这只取决于你想工作多努力。ClassWithMutableMutableImmutable

3赞 Blorgbeard 8/30/2016 #2

可以使用仅公开属性的接口和实现属性的私有类。get

public interface IImmutable {
    int Value { get; }
}

public class ClassWithImmutable{

    private Mutable _object;        
    public IImmutable Object { get { return _object; } }

    public ClassWithImmutable(){
        this._object = new Mutable();
        this._object.Value = 0;
    }

    private class Mutable : IImmutable {
        public int Value { get; set; }
    }

}

public class Demo{
    public static void Main(String[] args){
        ClassWithImmutable test = new ClassWithImmutable();
        IImmutable o = test.Object;
        o.Value = 1;    // fails
    }
}