代码比较简单,只作为简单的例子参考;
例子1
static void Main(string[] args)
{
UserInfo userInfo = new UserInfo();
userInfo.ID = 1;
userInfo.Name = "bailey";
userInfo.CreateDate = DateTime.Now;
userInfo.Number = Convert.ToDecimal(456.6467);
string values = string.Empty;
foreach (System.Reflection.PropertyInfo p in userInfo.GetType().GetProperties())
{
if (p.PropertyType == typeof(string))
{
values += string.Format("{0}='{1}', ", p.Name, p.GetValue(userInfo));
}
if (p.PropertyType == typeof(int)|| p.PropertyType == typeof(uint))
{
values += string.Format("{0}={1},", p.Name, p.GetValue(userInfo));
}
if (p.PropertyType == typeof(DateTime))
{
values += string.Format("{0}='{1}', ", p.Name, p.GetValue(userInfo));
}
if (p.PropertyType == typeof(decimal) || p.PropertyType == typeof(double)|| p.PropertyType == typeof(float))
{
values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
}
if (p.PropertyType == typeof(bool))
{
values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
}
if (p.PropertyType == typeof(sbyte))
{
values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
}
if (p.PropertyType == typeof(byte) || p.PropertyType == typeof(short) || p.PropertyType == typeof(ushort) )
{
values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
}
if (p.PropertyType == typeof(long) || p.PropertyType == typeof(ulong))
{
values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo));
}
// values +=string.Format( "{0}={1},", p.Name, p.GetValue(userInfo));
// Console.WriteLine("Name:{0} Value:{1}", p.Name, p.GetValue(userInfo));
}
Console.WriteLine(values);
Console.ReadLine();
}
例子2(已封装)
public async Task<ErrData<string>> CheckPropertiesAsync(QueryData<ResSBOMCheckBaseQuery> query)
{
var result = new ErrData<string>();
var dt = DateTime.Now;
StringBuilder strMsg = new StringBuilder();
try
{
await Task.Run(() =>
{
Type t = query.Criteria.VerificationObject.GetType();
var PropertyInfo = t.GetProperties();
foreach (var pi in PropertyInfo)
{
string name = pi.Name;
if (query.Criteria.resSBOMChecks.Where(c => c.Attribute == name).Count() > 0)
{
object values = pi.GetValue(query.Criteria.VerificationObject, null) as IComparable;
var chackList = query.Criteria.resSBOMChecks.Where(c => c.Attribute == name).ToList();
if (chackList.Where(ck => ck.Attributevalue == values.ToString()).Count() <= 0)
{
strMsg.Append(chackList[0].errorType.ToString());
strMsg.Append("/");
}
}
}
if (strMsg.ToString().Length > 1)
{
result.Data = strMsg.ToString().Substring(0, strMsg.ToString().Length - 1);
}
else
{
result.Data = strMsg.ToString();
}
});
}
catch (Exception ex)
{
result.SetInfo(ex.ToString(), -500);
}
result.ExpandSeconds = (DateTime.Now - dt).TotalSeconds;
return result;
}
每天进步一点,学无止境!