How does SET work with a property in C #?

I would like to know how to set works in a property when it does more than just the value of a private member variable. Say I have a private member in my class ( private int myInt ).

For example, I can make sure the return value is not negative

get
{
  if(myInt < 0)
    myInt = 0;
  return myInt;
}

With SET, all I can do is affect the private variable.

set { myInt = value; }

In any book, I have not seen how I can do more than that. How about if I do not do some operation before affecting the value of myInt? Let them say: If the value is negative, change the value 0 to myInt.

set
{
  //Check if the value is non-negative, otherwise affect the 0 to myInt
}

thanks for the help

+3
source share
7

, .

:

set
{
    if (value < 0)
        myInt = 0;
    else
        myInt = value;
}

( )

, .

, , .

Setters Getters , "" - . , , 1000 ( ). , , Get .

, , @StingyJack , .

+9

"". , :

set { 
  // Silently set to a more correct value
  myInt = value < 0 ? 0 : value; 
}

set { 
  // Always return error to caller
  if (value < 0) {
     throw new ArgumentException("value", "value cannot be negative.")
  }
  myInt = value; 
}

set { 
  // When debugging, warn the developer, in release adjust value silently
  Debug.Assert(value >= 0, "Value should 0 or larger");
  myInt = value < 0 ? 0 : value; 
}
+7

, - set. - value. , , -.

+5

:

set { myInt = value < 0 ? 0 : value; }

, value, Int... , value , , : )

+4

- , :

, -

(double to int ..), (Xml ).

class ThingWrapper
{
    public Thing Thing {get; set;}

    public int SomeProperty
    {
        get
        {
            return int.Parse(this.Thing.SomeProperty);
        }
        set
        {
            Thing.SomeProperty = value.ToString();
        }
    }
}

, - , , , , .

- , , , ( - ). , .

+2

, :

public int SomeValue
{
    get { return _SomeValue; }
    set { _SomeValue = this; }
}

:

public int SomeValue { get; set; }

public int get_SomeValue()
{
    return _SomeValue;
}

public void set_SomeValue(int value)
{
    _SomeValue = value;
}

, , , .

+1

, , , . , ...

Public Class MyClass

 Private m_myValue as String

 Public Property MyValue as String
  Get
   If String.IsNullOrEmpty(m_myValue) Then
    Return String.Empty
   Else
    Return m_myValue
   End If
  End Get
  Set (Value as String)
   If String.IsNull(m_myValue) = False Then
    m_myValue = Value
   End If
  End Set
 End Property

 Public Function GetLengthOfMyValue() as Integer
  Return m_myValue.Length
 End Function

End Class

, _len2 , , .

Dim _mc as New MyClass()
Dim _len1 as Integer = _mc.MyValue.Length
Dim _len2 as Integer = _mc.GetLengthOfMyValue()

, , , , , , .

  • ? ( , )?
  • , , ?

, .

0

Source: https://habr.com/ru/post/1744499/


All Articles