Type t = obj.GetType();//获得该类的Type
string keys = string.Empty;
string values = string.Empty;
foreach (PropertyInfo pi in t.GetProperties())
{
var name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
var value = pi.GetValue(obj, null);//用pi.GetValue获得值
var type = value?.GetType() ?? typeof(object);//获得属性的类型
if (null == name && null == value)
{
continue;
}
if (string.IsNullOrEmpty(keys))
{
keys += name;
}
else
{
keys += "," + name;
}
if (Type.Equals(type, typeof(DateTime)))//判断是否为自己设定的类型(举例为时间)
{
value = ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
}
if (string.IsNullOrEmpty(values))
{
values += "'"+value+"'";
}
else
{
values += "," + "'" + value + "'";
}
}
温馨提示:内容为网友见解,仅供参考