如下示例类
public class People { public bool View { get; set; } public bool Create { get; set; } public bool Edit { get; set; } public bool Delete { get; set; } }
1.以属性填充方式进行
public void Test1() { People entity = new People(); entity.View = true; entity.Create = true; entity.Delete = false; entity.Edit = true; }
2.以构造函数填充
public People(bool view, bool create, bool edit,bool delete) { this.View = view; this.Create = create; this.Edit = edit; this.Delete = delete; }
public void Test2() { People entity = new People(true,true,true,false); }
以此构造函数创建对象有如下缺点
(1)必须4个参数全部输入(不考虑c# 4.0缺省参数),必须重新构建新构造函数,如
public People(bool view, bool create) { this.View = view; this.Create = create; }
(2)构造函数一些容易造成混淆
有人说可以使用c#3.0语法,如下
public void Test3() { People entity = new People() {Edit=true, Create=false }; }
以上方式比较灵活,但是如果我要将属性变更为私有属性,如
private bool View { get; set; } private bool Create { get; set; } private bool Edit { get; set; } private bool Delete { get; set; }
但同时又想方便的在构造函数中设置参数,但又不要长长的构造器.这时候枚举就可以帮上忙
3.枚举
public People(PeoplePermissions options) { _options = options; } private PeoplePermissions _options;
public void Test4() { People entity = new People(PeoplePermissions.Create | PeoplePermissions.Delete); }枚举的操作还是比较麻烦的,用属性则比较友好,所以又可以用属性来包装枚举中的值,如
private bool Delete { get { return ReadFlag(PeoplePermissions.Delete); } set { WriteFlag(PeoplePermissions.Delete, value); } }
总结:
(1)构造函数中用枚举当参数非常方便
(2)取值非常麻烦
(3)封装成属性比较友好,但更费力气有好有坏吧,目前又想方便又想要属性,只能是这样了,否则是省掉第三步,但少了第三步,没有属性有时候代码写起来比较沮丧.
其实这个应用很广.WPF到处是这样的应用,FrameworkPropertyMetadata 就比较的典型