c#构造函数对string类型赋初值

 1 public class Stu
 2     {
 3         public Stu()
 4         {
 5             //当成员属性非常多难以一一赋值时,采用本方法。当然写代码逐一成员直接赋值效率更高。
 6             AssignEmptyStringMemberProperties();
 7         }
 8 
 9         /// <summary>
10         /// string类型成员赋空值(string.Empty)
11         /// 类似还可以写出:对int、datetime等处理
12         /// </summary>
13         public void AssignEmptyStringMemberProperties()
14         {
15             foreach (var property in this.GetType().GetProperties())
16             {
17                 if (property.PropertyType == typeof(string))
18                 {
19                     property.SetValue(this, string.Empty, null);
20                 }
21             }
22         }
23 
24         public long Id { get; set; }
25 
26         public string Name { get; set; }
27 
28         public string Sno { get; set; }
29 
30         public string Mobile { get; set; }
31 
32         public string IdCard { get; set; }
33 
34         public string Remark1 { get; set; }
35         public string Remark2 { get; set; }
36         public string Remark3 { get; set; }
37         public string Remark4 { get; set; }
38         public string Remark5 { get; set; }
39     }

主要就是利用反射获取本类中的所有属性,若是string类型则赋初值

posted on 2017-12-01 09:41  nlh774  阅读(2028)  评论(0编辑  收藏  举报