System.Reflection GetProperties方法不返回值

gsi*_*nni 24 .net c# reflection

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

public class DocumentA
{
    public string AgencyNumber = string.Empty;
    public bool Description;
    public bool Establishment;
}
Run Code Online (Sandbox Code Playgroud)

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

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

我正在做的就是调用以下内容,但它返回0

PropertyInfo[] pi = target.GetProperties(BindingFlags.Public | BindingFlags.Instance);
Run Code Online (Sandbox Code Playgroud)

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

我没有按照旧学校方式设置课程的原因是因为它有61个属性并且这样做会增加我的代码行数至少三倍.我会成为维护的噩梦.

Jon*_*eet 51

您尚未声明任何属性 - 您已声明了字段.这是与属性类似的代码:

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

    public DocumentA() 
    {
        AgencyNumber = "";
    }
}
Run Code Online (Sandbox Code Playgroud)

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