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

吃可爱长大的小学妹 提交于 2019-11-29 06:36:24

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.

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.

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;}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!