C# System.Reflection GetProperties方法不返回值

C# System.Reflection GetProperties方法不返回值,c#,.net,reflection,C#,.net,Reflection,有人能解释一下,如果类设置如下,为什么GetProperties方法不会返回公共值 public class DocumentA { public string AgencyNumber = string.Empty; public bool Description; public bool Establishment; } 我正在尝试建立一个简单的单元测试方法 该方法如下所示,它具有所有适当的using语句和引用 我所做的就是调用下面的函数,但它返回0 Propert

有人能解释一下,如果类设置如下,为什么
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个属性,这样做会使我的代码行数增加至少三倍。我将是维护的噩梦。

您还没有声明任何属性-您已经声明了字段。下面是具有属性的类似代码:

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

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

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

因为您现在声明类的方式是使用字段。如果要通过反射访问字段,应使用Type.GetFields()(请参阅Types.GetFields方法)

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

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

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

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

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

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

/**
*方法迭代车辆类字段(动态..)
*将每个字段重置为空
**/
公共无效重置(){
试一试{
Type myType=this.GetType();//获取指定类的类型句柄
FieldInfo[]myfield=myType.GetFields();//获取指定类的字段
for(int-pointer=0;pointer

请注意,GetFields()访问公共字段的原因很明显。

很明显,该类没有任何属性。只有字段。当你让班级像那样爆炸时,噩梦就开始了。使用公共字段需要更多的睡眠。我完全同意你使用属性而不是字段。我只是不知道正确的语法。我通常声明私有字段和公共getter和setter。我的问题是,我以为我在使用属性,而实际上我缺少{get,set}。谢谢你的澄清。这个答案真的帮助了我。谢谢你的回答。我只是把语法搞乱了。我通常不会这样声明属性。大多数tiem I都有公共属性和相应的私有字段。但是为什么呢?使用简写语法编译为相同的IL。编译器将为您生成后端字段。只有当您想在getter或setter中进行其他处理时,才需要更复杂的语法。这个答案解决了关于字段的最初问题,即使作者错误地在字段上使用了GetProperties()。非常感谢。
/**
 * 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
    }
}