源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-05-07 05:40 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C#编程获取实体类属性名和值的方法示例
本文实例讲述了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;
}

[b]PS:这里再为大家推荐一款本站的C#相关工具供大家参考使用:[/b] [b]JSON在线转换成C#实体类工具: [/b][url=http://tools.jb51.net/code/json2csharp]http://tools.jb51.net/code/json2csharp[/url] 更多关于C#相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/116.htm]C#数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/777.htm]C#遍历算法与技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/265.htm]C#数组操作技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/478.htm]C#面向对象程序设计入门教程[/url]》 希望本文所述对大家C#程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部