getter和setter的简写

getter和setter的简写

本文介绍了C#getter和setter的简写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If my understanding of the internal workings of this line is correct:

public int MyInt { get; set; }

然后在幕后执行此操作:

Then it behind the scenes does this:

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进行处理的一些对象具有许多属性,我希望有一种方法可以使用自动获取/设置方法,但在修改字段时仍可以设置IsDirty.

Which does not work. The thing is some of the objects I need to do the IsDirty on have dozens of properties and I'm hoping there is a way to use the auto getter/setter but still set IsDirty when the field is modified.

这是可能的吗?还是我必须辞职以使班上的代码量增加三倍?

Is this possible or do I just have to resign myself to tripling the amount of code in my classes?

推荐答案

您需要亲自处理:

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;}
}

没有可用的语法在仍使用自动属性机制的同时将自定义逻辑添加到设置器.您需要使用自己的后备字段来编写它.

There is no syntax available which adds custom logic to a setter while still using the automatic property mechanism. You'll need to write this with your own backing field.

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

This is a common issue - for example, when implementing INotifyPropertyChanged.

这篇关于C#getter和setter的简写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:04