【发布时间】:2011-06-18 08:51:16
【问题描述】:
我想获取所有具有空值的字段,但我什至没有获取任何字段:
[Serializable()]
public class BaseClass
{
[OnDeserialized()]
internal void OnDeserializedMethod(StreamingContext context)
{
FixNullString(this);
}
public void FixNullString(object type)
{
try
{
var properties = type.GetType().GetFields();
foreach (var property in from property in properties
let oldValue = property.GetValue(type)
where oldValue == null
select property)
{
property.SetValue(type, GetDefaultValue(property));
}
}
catch (Exception)
{
}
}
public object GetDefaultValue(System.Reflection.FieldInfo value)
{
try
{
if (value.FieldType == typeof(string))
return "";
if (value.FieldType == typeof(bool))
return false;
if (value.FieldType == typeof(int))
return 0;
if (value.FieldType == typeof(decimal))
return 0;
if (value.FieldType == typeof(DateTime))
return new DateTime();
}
catch (Exception)
{
}
return null;
}
}
然后我有一节课:
[Serializable()]
public class Settings : BaseClass
{
public bool Value1 { get; set; }
public bool Value2 { get; set; }
}
但是当我谈到
var properties = type.GetType().GetFields();
然后我得到 0 个字段,它应该找到 2 个字段。
type.getType().GetFields() 用错了吗?还是我将错误的类发送到基类?
【问题讨论】:
标签: c# class reflection