System.Reflection GetProperties方法不返回值 [英] System.Reflection GetProperties method not returning values

查看:63
本文介绍了System.Reflection GetProperties方法不返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can some one explain to me why the GetProperties method would not return public values if the class is setup as follows.

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

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

I am trying to setup a simple unit test method to play around with

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

The method is as follows and it has all the appropriate using statements and references.

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

All I'm doing is calling the following but it returns 0

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

但是,如果我使用私有成员和公共属性设置该类,则效果很好.

But if I setup the class with private members and public properties it works fine.

我之所以没有按传统方式设置课程,是因为它具有61个属性,这样做会使我的代码行增加到至少三倍.我将是一场维护噩梦.

The reason I didn't setup up the the class the old school way was because it has 61 properties and doing that would increase my lines of code to at least triple that. I would be a maintenance nightmare.

推荐答案

您尚未声明任何属性-您已经声明了 fields .这是带有属性的类似代码:

You haven't declared any properties - you've declared fields. Here's similar code with properties:

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

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

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

I would strongly advise you to use properties as above (or possibly with more restricted setters) instead of just changing to use Type.GetFields. Public fields violate encapsulation. (Public mutable properties aren't great on the encapsulation front, but at least they give an API, the implementation of which can be changed later.)

这篇关于System.Reflection GetProperties方法不返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆