拦截C#中的setter

时间:2015-06-04 20:22:46

标签: c#

我正在尝试学习C#,并且来自Java。我在C#中看过这个:

class A {
   public string x { get; set; } 
}

如果我想拦截setter上的传入值,该怎么办?

3 个答案:

答案 0 :(得分:3)

这只是

的语法糖
private string x;

public string X
{
    get { return this.x; }
    set { this.x = value; }
}

这实际上是编译器为您的代码输出的内容,但您无法直接访问字段x

如果您需要执行除设置和从字段中检索值之外的任何操作,请始终使用此长格式。

答案 1 :(得分:2)

您可以创建backing store

private string _x;
public string x {
   get {
       return _x;
   }
   set {
       // do something - you can even return, if you don't want the value to be stored

       // this will store the value
       _x = value;

       // do something else
   }
}

答案 2 :(得分:1)

首先,您应该创建一个私有属性,您将存储实际值。在get函数中,只返回该私有属性。在set方法中,您可以使用value关键字查看传入值,并在实际设置私有属性之前执行任何操作;

public class A
{
   private string xPrivate;
   public string X {
      get { return this.xPrivate; }
      set { this.xPrivate = value; }}
}