简体   繁体   中英

.NET Class Properties - Setter with parameter?

One of the nice features of .net is class Properties - wrapping gettter and setter of class field (which is private, but accessor methods are ussualy public). From outside of a class this Property looks as one field and does not flood intellisense with nomber of getters and setters.

Usual syntax is

private bool _isReadOnly;
public bool IsReadOnly
{
    get { return _isReadOnly; }
    set { _isReadOnly = value; }
}

or for implicit declaration it is

public bool IsReadOnly
{
get;
set;
}

This is very nice, both accessors can have even different access modifiers, eg. private setter.

My question is: does .NET support setters or getters with parameters? Like to have setter with two parameters - for example - one is value to set and other is bool which indicates something like "notify listeners about change" or "do not overwrite old value if newer value fails check" or something like that. Parameter for getter could be some option to format output or whether returned value should be clone of old etc.

Thank you. I do dot need it for any particular goal to achieve, so no need to post workarounds, i just wonder if there is something like this in .net Property.

No - a property is simply used to retrieve or set a value. For your examples, you'd need to use a method.

VB.NET supports parameters on properties.

C# doesn't.

c# 支持带参数的setter或getter。

Nope; however, you can make the get/set accessors have some nice check logic. If you have another field that you set (outside of the get/set) method, you can check against that field during your 'set' update to branch your logic based on a condition.

private bool positiveOnly;
private int _myNum;

public int MyNum
{ 
   get {return _myNum;}
   set
   {
      // use old if positive only and value less than 0
      _myNum = (positiveOnly && value < 0) ? _myNum : value;
   }
}

public void MyMethod()
{
   positiveOnly = true;
   MyNum = Convert.ToInt32(txtMyTextBox.Text);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM