当前位置: 移动技术网 > IT编程>开发语言>c# > C#编程获取实体类属性名和值的方法示例

C#编程获取实体类属性名和值的方法示例

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#编程获取实体类属性名和值的方法。分享给大家供大家参考,具体如下:

遍历获得一个实体类的所有属性名,以及该类的所有属性的值

//先定义一个类:
public class user
{
  public string name { get; set; }
  public string gender { get; set; }
  public string age { get; set; }
}
//实例化类,并给实列化对像的属性赋值:
user u = new user();
u.name = "ahbool";
u.gender = "男";
//输出此类的所有属性名和属性对应的值
response.write(getproperties(u));
//输出结果为: name:ahbool,gender:男,age:,
//遍历获取类的属性及属性的值:
public string getproperties<t>(t t)
{
  string tstr = string.empty;
  if (t == null)
  {
    return tstr;
  }
  system.reflection.propertyinfo[] properties = t.gettype().getproperties(system.reflection.bindingflags.instance | system.reflection.bindingflags.public);
  if (properties.length <= 0)
  {
    return tstr;
  }
  foreach (system.reflection.propertyinfo item in properties)
  {
    string name = item.name;
    object value = item.getvalue(t, null);
    if (item.propertytype.isvaluetype || item.propertytype.name.startswith("string"))
    {
      tstr += string.format("{0}:{1},", name, value);
    }
    else
    {
      getproperties(value);
    }
  }
  return tstr;
}

ps:这里再为大家推荐一款本站的c#相关工具供大家参考使用:

json在线转换成c#实体类工具:

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#数据结构与算法教程》、《c#遍历算法与技巧总结》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程

希望本文所述对大家c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网