close

IDE:VS2019

如果new class之後,這個class有資料了,但是參數很多,想要初始化可能會是像這樣

Person person = new Person();

person = new Person();

但是如果是綁定的物件,這樣會導致綁定遺失,要重新綁定

所以會變成這樣

person.Name = null;

person.Age = null;

這樣感覺很.......$@%@$%@$

今天突然想到一個寫法,想要把物件裡面屬性是String的,都初始化為Null

 var properties = person.GetType()
                   .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                   .Where(o => o.PropertyType == typeof(string));
       properties.ForEach(o => o.SetValue(_class, null));

這樣就快多了!!!

 

 

 

arrow
arrow
    文章標籤
    C# 初始化
    全站熱搜

    軒軒的爸媽 發表在 痞客邦 留言(0) 人氣()