Set only setter properties

I have an object model that has the following property:

public class SomeModel
{
   public string SomeString { get; set; }

   public void DoSomeWork()
   {
      ....
   }
}

I want the function to DoSomeWorkexecute automatically after changing the property SomeString. I tried this, but it does not work:

public string SomeString { get; set { DoSomeWork(); } }

What is the correct syntax?

+5
source share
5 answers

Use a private field instead, for example ...

public class SomeModel
{
    private string someString = "";

    public string SomeString {
        get { return this.someString; }
        set {
            this.someString = value;
            this.DoSomeWork();
        }
    }

   public void DoSomeWork()
   {
      ....
   }
}
+12
source

You cannot do this with automatic properties — you will need to create the "manual" property supported by the field.

private string _someString;

public string SomeString
{ 
   get { return _someString; }
   set 
   {
        _someString = value;
        DoSomeWork();
   }
}

(, ), AOP, PostSharp, - , .

+3

...

private string _someString;
public string SomeString { get { return _someString; } set { _someString = value; DoSomeWork(); } }
+2
private string _someString;

public string SomeString
{
    get
    {
       return _someString;
    }
    set 
    {
       DoSomeWork();
       _someString = value;
    }
}
+1

# # 3.0. , , . , - . .

public string Name{ get; set;}// auto-implemented property. no additional logic.

, . , , .

private string _Name;
public string Name
{
  get {return _Name;}
 set {
        _Name=value;
        DoSomething(); //Additional logic implemented.
     }
}
0

All Articles