Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

c# - System.Reflection GetProperties method not returning values

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

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

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = "";
    }
}

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...