使用属性显示数组类数据结构 [英] Exposing array-like data structure using properties
本文介绍了使用属性显示数组类数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
它建议将这种数据结构的克隆公开为属性,以便内部结构不会受到干扰。
有没有一个很好的解决方案?
public class Rule
{
}
public class RulesManager
{
列表< Rule> rules = new List< Rule>();
public List< Rule>规则
{
get {return rules; }
set {rules = value;
}
public void Add(Rule r)
{
rules.Add(r);
//添加后执行其他操作;
}
public void Delete(Rule r)
{
rules.Remove(r);
//删除后执行其他操作;
}
}
public class CallingCode
{
public static void Main()
{
RulesManager r = new RulesManager();
//选项1
r.Rules.Add(new Rule());
//选项2
r.Add(new Rule());
}
}
解决方案
返回克隆
,您可以使用规则返回只读版本的
。规则
。 AsReadOnly()
public IList< Rule>规则
{
get {return rules.AsReadOnly(); }
// set {rules = value; - 如果只读,不应该被允许设置!
}
请注意 IList
。
Its typical to expose internal data structures as properties to your business class. But when we have to expose array-like structures (like List<Rule> rules) we might encounter a problem of wrong usage (as in Option 1).
Its suggested to expose clone of such data structures as properties, so that internal structure does not get disturbed.
Does any one have a well-settled solution for this?
public class Rule
{
}
public class RulesManager
{
List<Rule> rules = new List<Rule>();
public List<Rule> Rules
{
get { return rules; }
set { rules = value; }
}
public void Add(Rule r)
{
rules.Add(r);
// Do something else after add;
}
public void Delete(Rule r)
{
rules.Remove(r);
// Do something else after delete;
}
}
public class CallingCode
{
public static void Main()
{
RulesManager r = new RulesManager();
// Option 1
r.Rules.Add(new Rule());
// Option 2
r.Add(new Rule());
}
}
解决方案
Instead of returning a Clone
, you can return a read-only version of rules
using rules.AsReadOnly()
.
public IList<Rule> Rules
{
get { return rules.AsReadOnly(); }
// set { rules = value; -- should not be allowed to set if read only!
}
Note the IList
.
这篇关于使用属性显示数组类数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文