.net C#检查类类型
我有一个通用的修剪对象的方法.net C#检查类类型,.net,c#-4.0,system.reflection,.net,C# 4.0,System.reflection,我有一个通用的修剪对象的方法 public static T GetTrimmedObject<T>(T model, bool isWantToEncodeStrings = false) where T : class { try { List<PropertyInfo> propertiesInfoCollection = model.GetType().GetProperties().ToList()
public static T GetTrimmedObject<T>(T model, bool isWantToEncodeStrings = false) where T : class
{
try
{
List<PropertyInfo> propertiesInfoCollection = model.GetType().GetProperties().ToList();
foreach (PropertyInfo item in propertiesInfoCollection)
{
Type type = item.PropertyType;
if (type == typeof(String))
{
dynamic value = item.GetValue(model, null);
if (!String.IsNullOrWhiteSpace(value))
{
item.SetValue(model, isWantToEncodeStrings ? HttpUtility.HtmlEncode(value.Trim()) : value.Trim(), null);
}
}
}
return model;
}
catch (Exception ex)
{
HandleAndLogException(ex, typeof(GlobalUtil));
return model;
}
}
public static T GetTrimmedObject(T model,bool isWantToEncodeStrings=false),其中T:class
{
尝试
{
List propertiesInfoCollection=model.GetType().GetProperties().ToList();
foreach(PropertiesInfo集合中的PropertyInfo项)
{
类型类型=item.PropertyType;
if(type==typeof(String))
{
动态值=item.GetValue(model,null);
如果(!String.IsNullOrWhiteSpace(值))
{
item.SetValue(model,isWantToEncodeStrings?HttpUtility.HtmlEncode(value.Trim()):value.Trim(),null);
}
}
}
收益模型;
}
捕获(例外情况除外)
{
HandleandLogeException(例如,typeof(GlobalUtil));
收益模型;
}
}
但当属性是类的类型时,我需要递归调用,这样嵌套的类属性也会被清除。
因此,我的问题是如何检查相同的类型?您可以检查Type.IsPrimitive是否为类类型,并递归调用给定类型的函数