我有以下属性和支持字段:
private Vector3 _positionB;
public Vector3 PositionB
{
get
{
if (_nodeB == null) return _positionB;
else return _nodeB.Position;
}
set
{
_positionB = value;
UpdateMesh();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,我有时会继续将值分配给类中的支持字段并跳过属性设置器(因此由于逻辑错误它不会自动更新)。
我更愿意通过属性强制分配,以便设置器随后运行相关函数。
有没有办法将其抽象出来以强制只分配给类中的属性?
鉴于类的任何其他成员始终具有对任何private字段的同等访问权限(因为您不能拥有范围仅限于属性的类级字段),您真正可以做的唯一事情就是(ab)使用ObsoleteAttribute触发编译器警告。
#pragma warning disable 0618抑制编译器警告PositionB。Obsolete(String,Boolean)构造函数来设置,bool error == true因为您无法抑制错误,只能抑制编译器信息消息和警告。但是(我认为)您可以设置.csproj项目属性以将警告 618 升级为错误,但这适用于所有出现的 CS0618,而不仅仅是这个特定的 C# 字段。
或者直接在记事本中编辑.csproj文件并将其添加到主<PropertyGroup>元素中:
<WarningsAsErrors>618</WarningsAsErrors>
Run Code Online (Sandbox Code Playgroud)例子:
class Foo
{
[Obsolete( "Do not use this field directly. Use the " + nameof(Foo.PositionB) + " property instead." )]
private Vector3 position3;
public Vector3 PositionB
{
get
{
#pragma warning disable 618 // Obsolete
if( this.nodeB == null ) return this.positionB;
else return this.nodeB.Position;
#pragma warning restore 618
}
set
{
#pragma warning disable 618 // Obsolete
this.positionB = value;
this.UpdateMesh();
#pragma warning restore 618
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以这段代码会导致编译器警告:
class Foo
{
// [...]
public void Bar()
{
this.positionB = 123; // this statement will cause a compiler warning
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1016 次 |
| 最近记录: |