当前位置: 移动技术网 > IT编程>开发语言>c# > C#通过属性名字符串获取、设置对象属性值操作示例

C#通过属性名字符串获取、设置对象属性值操作示例

2020年05月10日  | 移动技术网IT编程  | 我要评论
本文实例讲述了c#通过属性名字符串获取、设置对象属性值操作.分享给大家供大家参考,具体如下:#通过反射获取对象属性值并设置属性值0、定义一个类 public class user { public

本文实例讲述了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"

#获取对象的所有属性名称及类型

通过类的对象实现

 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
 }

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网