What does it means? [c#]
If we 开发者_Python百科define a property as public
property and in this property we have a protected
getter. what does it means? if property is public, what does defining a protected getter for that, means?
please see below code:
public ISessionFactory SessionFactory
{
protected get { return sessionFactory; }
set { sessionFactory = value; }
}
It means, that the getter can only be called by subclasses. The 'protected' before the getter so to say overwrites the 'public' for the getter part of the property.
In C# you are allowed to have getters and setters with access levels (see access modifiers) different than the overall property. This is the most common pattern
public class FooObject
{
public String Foo
{
get;
private set;
}
}
This allows objects instantiating FooObject to retrieve the value of Foo but not set it's value. The private modifier on the setter signifies that only FooObject itself has this ability (not including the use of reflection).
There are two advantages to this:
With the addition of automatic properties (no variables needed assign the get and set value), this allows the private setting of the property variable (it's created for you at compile time), to be done so without having to explicitly create the variable. Without this you couldn't use an automatic property, unless you always wanted the get and set function to be all public, all private etc.
It allows a level of abstraction, so that all methods whether public, private, or otherwise to go through the property and not directly access the private variable. See this question for more information.
In your instance other objects may set the session factory value, but only classes which inherit from it may retrieve it. Most of the time, if an object can set the value, it can also retrieve it, but there are instances where it would beneficial to not allow it. This is allowed, because the set event does not allow a greater amount of access than what was defined for the overall property.
The best example I can think of would be if on the set event, the set object was modified. For example, if it the set event was setting a connection object, and on the setting event, the connection string was added and the connection to the database was opened (In my example, I would probably refactor the code not to act in this way, but something like that could arise).
The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
http://msdn.microsoft.com/en-us/library/bcd5672a(VS.71).aspx
The protected get means that this property's getter can only be accessed from a inherited class of this class. the set is assumed public so this property can be setted publicly.
精彩评论