简体   繁体   English

只读嵌套对象属性

[英]Readonly nested object properties

I'm having a problem defining these 2 classes: 我在定义这两个类时遇到问题:

public class Article
{
    public Article(long ID, string Name, ArticleFamily Family)
    {
        //...Initializer...
    }
    public ArticleFamily Family { get; set; }
    //Other props...
}

public class ArticleFamily
{
    public ArticleFamily(int ID, string Description)
    {
        //...Initializer...
    }
    public int ID { get; private set; }
    public string Description { get; set; }
}

I have a collection of Article and each one belongs to a family. 我收藏了一篇文章 ,每个文章都属于一个家庭。
Now, given that I have a certain ArticleFamily object I should be able to change its Description and it gets eventually persisted to a DataBase. 现在,考虑到我具有某个ArticleFamily对象,我应该能够更改其Description并将其最终保存到数据库中。 (I left out that part for simplicity) (为简单起见,我省略了该部分)
But I should not be able to do this: 但是我不应该这样做:

Article art = SomeMethodReturningArticle();
art.Family.Description = "SomeOtherValue";

I should be able to change the Family of an Article entirely, replacing it with a new ArticleFamily object, but I shouldn't be able to change just the description. 我应该能够完全更改文章系列,而用新的ArticleFamily对象代替它,但是我不能仅更改描述。
Should I create a copy of the ArticleFamily class with readonly properties like this: 我是否应该使用如下只读属性创建ArticleFamily类的副本:

public class ArticleFamilyReadonly
{
    ArticleFamily _family;
    public ArticleFamilyReadonly(ArticleFamily Family)
    {
        _family = Family;
    }
    public int ID { get { return _family.ID; } }
    //etc...
}

How can I do this in a clean way? 我怎样才能做到这一点?

Here's what I threw together in LinqPad: 这是我在LinqPad中一起提交的内容:

void Main()
{
    var art = new Article(1,"2", new ArticleFamily(1, "Test"));
    art.Family.Description = "What?"; // Won't work

    var fam = art.Family as ArticleFamily;
    fam.Description = "This works"; // This works...

}

public class Article
{
    public Article(long ID, string Name, IArticleFamily Family)
    {
        //...Initializer...
    }
    public IArticleFamily Family { get; set; }
    //Other props...
}

public class ArticleFamily : IArticleFamily
{
    public ArticleFamily(int ID, string Description)
    {
        //...Initializer...
    }
    public int ID { get; private set; }
    public string Description { get; set; }
}

public interface IArticleFamily
{
    int ID { get; }
    string Description { get;}
}

Cannot edit directly from the Article object unless cast to ArticleFamily object. 除非强制转换为ArticleFamily对象,否则无法直接从Article对象进行编辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM