Using Reflection to determine which Fields are backing fields of a Property

后端 未结 3 1157
星月不相逢
星月不相逢 2020-12-17 17:58

I\'m using reflection to map out objects. These objects are in managed code but I have no visibility into their source code, underlying structure, etc. other than through re

相关标签:
3条回答
  • 2020-12-17 18:30

    You can ignore all properties completely. If a property doesn't have a backing field, then it simply doesn't consume any memory.

    Also, unless you're willing to (try to) parse CIL, you won't be able to get such mapping. Consider this code:

    private DateTime today;
    
    public DateTime CurrentDay
    {
        get { return today; }
    }
    

    How do you expect to figure out that there is some relation between the today field and the CurrentDay property?

    EDIT: Regarding your more recent questions:

    If you have property that contains code like return 2.6;, then the value is not held anywhere, that constant is embedded directly in the code.

    Regarding string: string is handled by CLR in a special way. If you try to decompile its indexer, you'll notice that it's implemented by the CLR. For these few special types (string, array, int, …), you can't find their size by looking at their fields. For all other types, you can.

    0 讨论(0)
  • 2020-12-17 18:34

    To answer your other question:Under what circumstances do properties not have backing fields?

    public DateTime CurrentDay
    {
        get { return DateTime.Now; }
    }
    

    or property may use any other number of backing fields/classes

    public string FullName 
    {
        get {return firstName + " " + lastName;}
    }
    
    0 讨论(0)
  • 2020-12-17 18:53

    The name of a property's backing field is a compiler implementation detail and can always change in the future, even if you figure out the pattern.

    I think you've already hit on the answer to your question: ignore all properties.

    Remember that a property is just one or two functions in disguise. A property will only have a compiler generated backing field when specifically requested by the source code. For example, in C#:

    public string Foo { get; set; }
    

    But the creator of a class need not use compiler generated properties like this. For example, a property might get a constant value, multiple properties might get/set different portions of a bit field, and so on. In these cases, you wouldn't expect to see a single backing field for each property. It's fine to ignore these properties. Your code won't miss any actual data.

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