c#反射判判断某个对象的某个属性是否string类型

2025-02-23 12:31:40
推荐回答(1个)
回答1:

public bool IsString(object obj,string propertyName)
{
if(obj==null)

{
throw new ArgumentNullException("obj");

}

Type type = obj.GetType();

PropertyInfo property = type.GetProperty(propertyName);

if(property==null)

{
throw new ArgumentException("不存在属性"+propertyName+"!","propertyName");

}

bool result=typeof(string).Equals(property.PropertyType);

if (result&&property.GetValue(obj)==null)

{
property.SetValue(obj,string.Empty);
}

return result;

}