【问题标题】:System.Reflection GetProperties method not returning valuesSystem.Reflection GetProperties 方法不返回值
【发布时间】:2011-10-20 15:19:08
【问题描述】:

有人可以向我解释为什么如果类设置如下,GetProperties 方法不会返回公共值。

public class DocumentA
{
    public string AgencyNumber = string.Empty;
    public bool Description;
    public bool Establishment;
}

我正在尝试设置一个简单的单元测试方法来玩

该方法如下,它具有所有适当的 using 语句和引用。

我所做的只是调用以下内容,但它返回 0

PropertyInfo[] pi = target.GetProperties(BindingFlags.Public | BindingFlags.Instance);

但是,如果我使用私有成员和公共属性设置类,它就可以正常工作。

我没有以老式方式设置课程的原因是它有 61 个属性,这样做会使我的代码行数至少增加三倍。我将成为维护的噩梦。

【问题讨论】:

  • 这很明显,该类没有任何属性。只有字段。当你让班级像那样爆炸时,噩梦就开始了。使用公共字段需要更多的睡眠。

标签: c# .net reflection


【解决方案1】:

您还没有声明任何属性 - 您已经声明了 fields。这是带有属性的类似代码:

public class DocumentA
{
    public string AgencyNumber { get; set; }
    public bool Description { get; set; }
    public bool Establishment { get; set; }

    public DocumentA() 
    {
        AgencyNumber = "";
    }
}

我强烈建议您使用上述属性(或者可能使用更多受限的设置器),而不是仅仅更改为使用Type.GetFields。公共字段违反封装。 (公共可变属性在封装方面不是很好,但至少它们提供了一个 API,稍后可以更改其实现。)

【讨论】:

  • 我完全同意你关于使用属性而不是字段的观点。我只是不知道正确的语法。我通常声明私有字段和公共 getter 和 setter。我的问题是我以为我在使用属性,而实际上我错过了 {get,set}。感谢您的澄清。
  • 这个答案真的帮助了我
【解决方案2】:

因为您现在声明类的方式是使用字段。如果你想通过反射访问字段,你应该使用 Type.GetFields() (参见 Types.GetFields Method1

我现在不知道您使用的是哪个版本的 C#,但 C# 2 中的属性语法已更改为以下内容:

public class Foo
{
  public string MyField;
  public string MyProperty {get;set;}
}

这是否有助于减少代码量?

【讨论】:

  • 感谢您的回答。我只是把我的语法打乱了。我通常不会以这种方式声明属性。大多数 tiem 我都有相应的私有字段的公共属性。
  • 但是为什么呢?使用简写语法编译为相同的 IL。编译器为您生成后端字段。当您想在 getter 或 setter 中进行一些其他处理时,您只需要更复杂的语法。
【解决方案3】:

我看到这个帖子已经有四年了,但我对所提供的答案仍然不满意。 OP 应该注意,OP 指的是字段而不是属性。要动态重置所有字段(扩展证明),请尝试:

/**
 * method to iterate through Vehicle class fields (dynamic..)
 * resets each field to null
 **/
public void reset(){
    try{
        Type myType = this.GetType(); //get the type handle of a specified class
        FieldInfo[] myfield = myType.GetFields(); //get the fields of the specified class
        for (int pointer = 0; pointer < myfield.Length ; pointer++){
            myfield[pointer].SetValue(this, null); //takes field from this instance and fills it with null
        }
    }
    catch(Exception e){
        Debug.Log (e.Message); //prints error message to terminal
    }
}

请注意,GetFields() 出于显而易见的原因只能访问公共字段。

【讨论】:

  • 这个答案解决了关于字段的最初问题,即使作者错误地在字段上使用 GetProperties()。谢谢!
【解决方案4】:

如前所述,这些是字段而不是属性。属性语法为:

public class DocumentA  { 
    public string AgencyNumber { get; set; }
    public bool Description { get; set; }
    public bool Establishment { get; set;}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2021-08-23
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多