【轉】C#通過屬性名字符串獲取、設置對象屬性值


原文地址:https://www.cnblogs.com/willingtolove/p/12198871.html

#通過反射獲取對象屬性值並設置屬性值
0、定義一個類
1、通過屬性名(字符串)獲取對象屬性值
2、通過屬性名(字符串)設置對象屬性值
#獲取對象的所有屬性名稱及類型
#判斷對象是否包含某個屬性

#通過反射獲取對象屬性值並設置屬性值

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"

#獲取對象的所有屬性名稱及類型

通過類的對象實現

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

通過類實現

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
 }

 


免責聲明!

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



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