我在定义这两个类时遇到问题:
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; }
}
我有文章的集合,每个人都属于一个家庭 现在,鉴于我有一个 ArticleFamily 对象,我应该能够更改其描述,并最终将其持久保存到DataBase。 (为简单起见,我省略了那部分) 但我不应该这样做:
Article art = SomeMethodReturningArticle();
art.Family.Description = "SomeOtherValue";
我应该能够完全更改文章的系列,将其替换为新的 ArticleFamily 对象,但我不能仅仅更改说明。
我应该使用这样的只读属性创建 ArticleFamily 类的副本:
public class ArticleFamilyReadonly
{
ArticleFamily _family;
public ArticleFamilyReadonly(ArticleFamily Family)
{
_family = Family;
}
public int ID { get { return _family.ID; } }
//etc...
}
我怎样才能以干净的方式做到这一点?
答案 0 :(得分:2)
这是我在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;}
}
除非转换为ArticleFamily对象,否则无法直接从Article对象进行编辑。