开发者

C# anonymous backing fields with non-auto properties

I want to make a private member variable that is private even to the class that owns it, and can ONLY be accessed by its getters and setters.开发者_C百科 I know you can do this with auto-properties like

private int MyInt{ get; set;}

But I want to be able to modify the getter and setter so (for example) I could log how many times the field has been set (even by the owning class). Something like this

private int MyInt
{
    get{ return hiddenValue; }
    set{ hiddenValue = value; Console.Out.WriteLine("MyInt has been set");}
}

where "hiddenValue" is the member that is only accessible in the getter and setter. Why? because I'm a paranoid defensive programmer, I don't even trust myself :p.

Is this possible in C#? and if so, what is the syntax?

Thanks.


You really should trust yourself.

And no, you can't make a variable so private even the encapsulating class can't see it.

If you really want this, you could encapsulate the value in a nested class, which would be able to cover its own privates.

class Foo 
{
    class Bar // nested
    {
        private int _value;
        public int Value 
        {
            get { return _value; }
            set { _value = value; /* logic */ }
        }
    }
}

Foo can instantiate a Bar, get at bar.Value, but it cannot get to _value.


Is not possible with any language in .Net. And is good. Defensive coding is good, but when becomes paranoid, it makes go crazy other developers who need to maintain it.


Aspect-Oriented Programming (AOP) might help, which in a nutshell, allowing you to inject code of your choice before and/or after method calls.

Check out http://code.google.com/p/easyprop/ which is an AOP library specifically designed for watching property changes, and there is examples for working with auto-properties.

NB: I haven't used the library yet, but it looks right up your alley.


No, this isn't possible in C#.

Your best bet is probably to become less paranoid. :P


What you are trying to do, can not be achieved in .NET.

Even the hidden backing field will be visible in IL code. Meaning while you can't see it at design time (in VS) it will be there after the compile.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜