System.Reflection GetProperties method not returning values

前端 未结 4 1131
情书的邮戳
情书的邮戳 2020-12-17 08:19

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
         


        
相关标签:
4条回答
  • 2020-12-17 08:56

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

    0 讨论(0)
  • 2020-12-17 08:56

    Because the way you have declared your class now is using Fields. If you want to access the fields trough reflection you should use Type.GetFields() (see Types.GetFields Method1)

    I don't now which version of C# you're using but the property syntax has changed in C# 2 to the following:

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

    Wouldn't this help in reducing the amount of code?

    0 讨论(0)
  • 2020-12-17 09:04

    As mentioned, these are fields not properties. The property syntax would be:

    public class DocumentA  { 
        public string AgencyNumber { get; set; }
        public bool Description { get; set; }
        public bool Establishment { get; set;}
    }
    
    0 讨论(0)
  • 2020-12-17 09:15

    I see this thread is already four years old, but none the less I was unsatisfied with the answers provided. OP should note that OP is referring to Fields not Properties. To dynamically reset all fields (expansion proof) try:

    /**
     * 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
        }
    }
    

    Note that GetFields() only has access to public fields for obvious reasons.

    0 讨论(0)
提交回复
热议问题