如果字段定义为自动属性,如何获取字段的值?



如果字段定义为自动属性,如何获取字段的值?
我不知道为什么,但是我第一次遇到如此简单的任务,其中有这样一种无法解释的方法,称为GetValue,它不能按我想要的方式工作,并且通常会抛出各种异常而不是做它原来的简单工作。

一些代码例如:

Class A
{
   public int Age { get; set;}
}

现在假设在反射之后,我将 A 实例的字段保存在 FiledInfo[] 的结构中。
现在我在上面的数组中找到了相关的字段信息,他的名字是:
{Int32 k__BackingField}听起来很奇怪,无论如何..
如何使用 GetValue() 来获取 int 值?正如我所说,我尝试了很多事情。

编辑:(这是部分简化的代码 - 不要生气)

private static string foo1<T>(T o)
        {
            var type = o.GetType();
            var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
           ....
            foo(fields);
         }
}
private static void foo(FieldInfo[] fields)  
        {
            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsValueType)
                {
                    var fieldNameLength = field.Name.IndexOf(">") - (field.Name.IndexOf("<")+1);
                    var fieldName = field.Name.Substring(field.Name.IndexOf("<")+1, fieldNameLength);
                    var fieldValue = field.ReflectedType.GetProperty(fieldName).GetValue(field.ReflectedType, null)
                }
             }
}
A a = new A() { Age = 33 };
var age = a.GetType().GetProperty("Age").GetValue(a);

而不是var fieldValue = field.ReflectedType.GetProperty(fieldName).GetValue(field.ReflectedType, null)你应该只有: var fieldValue = field.GetValue(o, null) 请注意,您需要传入o实例。真的,你应该按照L.B发布的内容,通过名字找到你的财产,或者如果你不知道这个名字,通过myType.GetProperties

枚举它们。

下面是修改为使用属性的代码:

private static void foo1<T>(T o)
{
    var type = o.GetType();
    var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
    foo(properties, o);
}
private static void foo(PropertyInfo[] properties, object o)
{
    foreach (PropertyInfo property in properties)
    {
        if (property.PropertyType.IsValueType)
        {
            var propertyValue = property.GetValue(o, null);
            //do something with the property value?
        }
    }
}
编辑:你可能想确保属性有一个getter(参见:

你如何只找到同时具有getter和setter的属性?),或者它可能是一个自动属性(参见:如何找出一个属性是否是带有反射的自动实现的属性?)但我猜这对你来说不一定是必需的, 可能只是正确使用GetValue方法或如何使用反射来检查类型。

编辑:如果您仍然希望使用字段,请使用字段的相同代码:

private static void foo1<T>(T o)
{
    var type = o.GetType();
    var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
    foo(fields, o);
}
private static void foo(FieldInfo[] fields, object o)
{
    foreach (FieldInfo field in fields)
    {
        if (field.FieldType.IsValueType)
        {
            var fieldValue = field.GetValue(o);
            //do something with the field value?
        }
    }
}

最新更新