1

我对 System.Reflection 有点问题。请看附件代码:

class Program
{
    public static FieldInfo[] ReflectionMethod(object obj)
    {
        var flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
        return obj.GetType().GetFields(flags);
    }
        static void Main()
    {
        var test = new Test() { Id = 0, Age = 12, Height = 24, IsSomething = true, Name = "Greg", Weight = 100 };
        var res = ReflectionMethod(test);
    }
}

    public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public bool IsSomething { get; set; }
    public int Weight { get; set; }
    public int Height { get; set; }
    public int CalculationResult => Weight * Height;

    public Test()
    {

    }
}

似乎 getfields 方法没有获取计算的属性 CalculationResult。我假设我需要使用另一个标志,但我不知道它是哪一个。

在此先感谢,如有必要,我会很乐意提供更多信息。

4

2 回答 2

4

那是因为它是一个属性而不是一个字段。

=>是作为属性的 getter 的语法糖。所以它等价于:

public int CalculationResult 
{ 
   get 
   { 
      return Weight * Height; 
   }
}

所以你需要使用.GetProperties(flags)

于 2016-08-01T17:02:01.693 回答
2

好吧,分析这行代码:

public int CalculationResult => Weight * Height;

也可以简化为(没有 C# 6.0 语法糖):

public int CalculationResult {get { return Weight*Height; } }

编译器不会创建支持字段,因为它不是自动属性,这就是为什么它不在通过反射调用从类中检索到的字段中。

如果您将其更改为public int CalculationResult { get; }它将创建该字段并将显示在列表中。

于 2016-08-01T17:04:24.707 回答