C# 反射怎么判断属性是int还是datetime,或者其他值类型

反射的时候,只有一个IsValueType判断是否是值类型,那我怎么来判断是int 还是bool,或者其他值类型呢

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 + "'";
}
}

温馨提示:内容为网友见解,仅供参考
第1个回答  2014-08-21
bool telo=true;//这只是示例,不管什么类型都可用下面语句取
telo.GetType().Name.ToString();

gettype()获取system.type,然后用name取类型名,取出来就是类型
第2个回答  2014-08-21
public class A
{
public int Property1 { get; set; }
}
A aa = new A();
Type type = aa.GetType();//获取类型
System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1");
判断它的propertyInfo.PropertyType.FullName
第3个回答  2014-08-21
reflecttype == typeof( int ) or reflecttype == typeof( bool )
应该这样判断吧本回答被提问者采纳
相似回答