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類型則賦初值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM