我正在使用一个设置私有(private)属性来做额外的工作。 问题是,有时我会设置变量 而不是 属性。
我想知道是否有办法避免这种情况。
private int _directionX = -1;
private int DirectionX
{
get
{
return _directionX;
}
set
{
_directionX = value;
ExtraWork();
}
}
private void Start()
{
// the problem is that I can do :
_directionX = 0;
// and so, property is bypassed :/
}
感谢阅读! 西奥
PS:我正在使用 Unity 2019 并将 API 兼容性级别设置为 .NET 4.x Equivalent
最佳答案
你可以使用 [<a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute%28v=vs.110%29.aspx" rel="noreferrer noopener nofollow">System.ComponentModel.EditorBrowsable</a>(<a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsablestate%28v=vs.110%29.aspx" rel="noreferrer noopener nofollow">System.ComponentModel.EditorBrowsableState.Never</a>)]
从 IntelliSense 中隐藏它。无论如何,如果您输入它,您仍然可以使用它,但不会自动完成它。
最终只有真正禁止自己使用它的方法,可能会定义自己的属性并配置类似 Resharper 的东西来将具有此属性的字段的使用标记为错误,但我不确定 Resharper 是否可以像这样配置。
关于c# - 即使有私有(private)字段也强制使用私有(private)属性(property)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57067392/