通过反射获得场 [英] get fields with reflection
本文介绍了通过反射获得场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取所有具有空值的字段,但我什至没有得到任何字段:
I want to get all fields that have null values but i aint even getting any fields:
[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个字段。
then i get 0 fields, it should find 2 fields.
type.getType()。GetFields()使用不正确吗?还是我向基类发送了错误的类?
Is type.getType().GetFields() wrong to use ? or am i sending in the wrong class to the base class?
推荐答案
Type.GetFields 方法返回所有公共字段。编译器自动为您生成的字段是私有的,因此您需要指定正确的 BindingFlags
。
Type.GetFields methods returns all public fields. Fields that the compiler autogenerates for you are private, so you need to specify correct BindingFlags
.
type.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
这篇关于通过反射获得场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文