开发者

Get the private field by properties with reflection C#

开发者 https://www.devze.com 2023-03-21 01:01 出处:网络
On my job I work with a v2.0 project. I need know which is the private field that is related to each property

On my job I work with a v2.0 project. I need know which is the private field that is related to each property

class Foo {

private string _bar;
public string BigBar
{
    get { return _bar; }
}}

Someone know 开发者_如何转开发how can I check this relation with reflection


If you're looking for backing fields of auto-like-properties, then the only way is to look at the generated IL, with a tool like Mono.Cecil, for example.

You'll have to look for a specific IL pattern, and also have to check if the backing field is only used in the property, and nowhere else.

The pattern would be the generated IL for this chunk of code:

private string _foo;
public string Foo { get { return _foo; } set { _foo = value; } }

(get and set are optional, but at least one must be present)


What you need is a decompiler to see the internal working of the classes:

Decompilers


While you could only do this with Reflection for Auto-implemented properties, consider using this open-source decompilation library: http://wiki.sharpdevelop.net/ILSpy.ashx. You can decompile the relevant methods and see what they do.

0

精彩评论

暂无评论...
验证码 换一张
取 消