//获取实体类里面所有的名称、值、DESCRIPTION值
public string getProperties(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;
}
设置 属性值:
/// 获取类中的属性值
///
///
///
///
public string GetModelValue(string FieldName, object obj)
{
try
{
Type Ts = obj.GetType();
object o = Ts.GetProperty(FieldName).GetValue(obj, null);
string Value = Convert.ToString(o);
if (string.IsNullOrEmpty(Value)) return null;
return Value;
}
catch
{
return null;
}
}
///
/// 设置类中的属性值
///
///
///
///
public bool SetModelValue(string FieldName,string Value, object obj)
{
try
{
Type Ts = obj.GetType();
object v = Convert.ChangeType(Value, Ts.GetProperty(FieldName).PropertyType);
Ts.GetProperty(FieldName).SetValue(obj, v, null);
return true;
}
catch
{
return false;
}
}