C#通過屬性名字符串獲取、設置對象屬性值操作示例
更新時間:2020年03月13日 12:07:21 作者:willingtolove
這篇文章主要介紹了C#通過屬性名字符串獲取、設置對象屬性值操作,結合實例形式總結分析了C#通過反射獲取對象屬性值并設置屬性值,獲取對象的所有屬性名稱及類型等相關操作技巧,需要的朋友可以參考下
本文實例講述了C#通過屬性名字符串獲取、設置對象屬性值操作.分享給大家供大家參考,具體如下:
#通過反射獲取對象屬性值并設置屬性值
0、定義一個類
public class User { public int Id { get; set; } public string Name { get; set; } public string Age { get; set; } }
1、通過屬性名(字符串)獲取對象屬性值
User u = new User(); u.Name = "lily"; var propName = "Name"; var propNameVal = u.GetType().GetProperty(propName).GetValue(u, null); Console.WriteLine(propNameVal);// "lily"
2、通過屬性名(字符串)設置對象屬性值
User u = new User(); u.Name = "lily"; var propName = "Name"; var newVal = "MeiMei"; u.GetType().GetProperty(propName).SetValue(u, newVal); Console.WriteLine(propNameVal);// "MeiMei"
#獲取對象的所有屬性名稱及類型
通過類的對象實現(xiàn)
User u = new User(); foreach (var item in u.GetType().GetProperties()) { Console.WriteLine($"propName:{item.Name},propType:{item.PropertyType.Name}"); } // propName: Id,propType: Int32 // propName:Name,propType: String // propName:Age,propType: String
通過類實現(xiàn)
foreach (var item in typeof(User).GetProperties()) { Console.WriteLine($"propName:{item.Name},propType:{item.PropertyType.Name}"); } // propName: Id,propType: Int32 // propName:Name,propType: String // propName:Age,propType: String
#判斷對象是否包含某個屬性
static void Main(string[] args) { User u = new User(); bool isContain= ContainProperty(u,"Name");// true } public static bool ContainProperty( object instance, string propertyName) { if (instance != null && !string.IsNullOrEmpty(propertyName)) { PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName); return (_findedPropertyInfo != null); } return false; }
將其封裝為擴展方法
public static class ExtendLibrary { /// <summary> /// 利用反射來判斷對象是否包含某個屬性 /// </summary> /// <param name="instance">object</param> /// <param name="propertyName">需要判斷的屬性</param> /// <returns>是否包含</returns> public static bool ContainProperty(this object instance, string propertyName) { if (instance != null && !string.IsNullOrEmpty(propertyName)) { PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName); return (_findedPropertyInfo != null); } return false; } } static void Main(string[] args) { User u = new User(); bool isContain= u.ContainProperty("Name");// true }
更多關于C#相關內(nèi)容感興趣的讀者可查看本站專題:《C#數(shù)據(jù)結構與算法教程》、《C#遍歷算法與技巧總結》、《C#數(shù)組操作技巧總結》及《C#面向?qū)ο蟪绦蛟O計入門教程》
希望本文所述對大家C#程序設計有所幫助。
相關文章
WinForm判斷關閉事件來源于用戶點擊右上角“關閉”按鈕的方法
這篇文章主要介紹了WinForm判斷關閉事件來源于用戶點擊右上角“關閉”按鈕的方法,涉及C#針對WinForm事件的判定技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09C# 漢字轉(zhuǎn)拼音實例(支持GB2312字符集中所有漢字)
本篇文章主要介紹了C# 漢字轉(zhuǎn)拼音實例(支持GB2312字符集中所有漢字) ,非常具有實用價值,需要的朋友可以參考下。2016-12-12