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); //值
string des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值
if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
tStr += string.Format("{0}:{1}:{2},", name, value, des);
}
else
{
getProperties(value);
}
}
return tStr;
}
本文介绍了一种使用C#反射技术来获取任意实体类的所有属性名称、值及描述的方法。通过实例演示了如何遍历对象的所有公共实例属性,并获取其名称、值以及通过DescriptionAttribute注解提供的描述。
3050

被折叠的 条评论
为什么被折叠?



