Answer the question
In order to leave comments, you need to log in
What is this construct called in C#?
What is the name of such a structure? Namely, get, return... What does it actually do?
private Matrix transform;
public Matrix Transform
{
get { return transform; }
}
Answer the question
In order to leave comments, you need to log in
getter (property).
It allows you to return an object of type Matrix called transform, which is stored in a private "Scope". And this is the default theme.
Suppose there is an object that only stores something in itself; private string my_string = "что-то";
it is in the "private" scope - i.e. available for use only within the class where it is located. In another class, it (my_string) cannot be accessed and modified. And ideally, this is how it should be done so that the created objects are available only where necessary, and not everywhere ...
then we create a getter (which only gives the value of the my_string object, while storing nothing in itself (only a link),
private string my_string = "что-то";
public string My_String { get { return my_string ; } }
private string my_string = "что-то";
public string My_String { get { return my_string ; } set { my_string = value; }}
//получить данные из my_string (get)
var temp = My_String;
//записать/установить/изменить данные в my_string (set)
My_String = "я тебя изменяю"; // в этом случае в будет не my_string = "что-то", а my_string = "я тебя изменяю"
Tom Nolane and flafy4 Getters and setters are needed not only to "output a private variable".
If private variables are hidden in a "private scope" then someone needs it. What prevents you from simply changing the access modifier of the field by making it accessible from the outside, than to fence some getters / setters?
There are a bunch of more interesting uses for getters and setters, such as
notifying when an object's state has changed:
string _StateValue;
public string stateValue
{
get {return _StateValue; }
set
{
_StateValue = value;
OnStateValueChanged(value); //этот метод генерирует событие на которое подписаны все кому интересно изменения этого поля, например при изменении поля могут по событию перерисовываться форма
}
}
string _CaсhedValue = null;
string cachedValue
{
get
{
if (_CachedValue == null)
{
_CachedValue = CreateValue(); //этот метод вычисляет значение
}
return _CachedValue;
}
}
PointF _Start;
PointF _Stop;
PointF center
{
get
{
return new PointF((_Start.X+_Stop.X)/2,(_Start.Y+_Stop.Y)/2);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question