C# getter 和 setter 简写

标签 c# getter-setter shorthand

如果我对这条线的内部运作的理解是正确的:

public int MyInt { get; set; }

然后它在幕后这样做:

private int _MyInt { get; set; }
Public int MyInt {
    get{return _MyInt;}
    set{_MyInt = value;}
}

我真正需要的是:

private bool IsDirty { get; set; }

private int _MyInt { get; set; }
Public int MyInt {
    get{return _MyInt;}
    set{_MyInt = value; IsDirty = true;}
}

但我想这样写:

private bool IsDirty { get; set; }

public int MyInt { get; set{this = value; IsDirty = true;} }

这是行不通的。问题是我需要在其上执行 IsDirty 的一些对象具有许多属性,我希望有一种方法可以使用自动 getter/setter,但在修改字段时仍然设置 IsDirty。

这可能吗,还是我只能听天由命,让我的类(class)中的代码量增加三倍?

最佳答案

你需要自己处理:

private bool IsDirty { get; set; }

private int _myInt; // Doesn't need to be a property
Public int MyInt {
    get{return _myInt;}
    set{_myInt = value; IsDirty = true;}
}

没有可用的语法在仍然使用自动属性机制的同时向 setter 添加自定义逻辑。您需要使用自己的支持字段编写此内容。

这是一个常见问题 - 例如,在实现 INotifyPropertyChanged 时。

关于C# getter 和 setter 简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5009823/

相关文章:

C# out 关键字的含义以及它在 PHP 中是否具有等效项?

c# - 如何使一个 ObservableCollection 依赖于另一个

c# - 使用 .NET XML 序列化在附加元素中包装序列化属性

python - 什么时候将事物存储为实例的一部分与返回它们?

javascript - 如何在 Javascript 对象(类)中使用 setter 和 getter?

properties - C++/CLI 速记属性

c# - Log4Net 不适用于我的海关属性

java - bean : accessors vs attributes

c - C/C++ 的简写和快捷方式

javascript - 我怎样才能默认对象?