gpt4 book ai didi

c# - 在 C# 中将实例变量的使用限制为单个方法

转载 作者:行者123 更新时间:2023-12-03 08:28:29 25 4
gpt4 key购买 nike

我希望能够将实例变量的使用限制为一种方法,并且其他用法不应该是可能的(编译错误或警告)。例如

public class Example
{
public string Accessor()
{
if (SuperPrivate == null) // allowed
{
SuperPrivate = "test"; // allowed
}

return SuperPrivate; // allowed
}

private string SuperPrivate;

public void NotAllowed()
{
var b = SuperPrivate.Length; // access not allowed
SuperPrivate = "wrong"; // modification not allowed
}

public void Allowed()
{
var b = Accessor().Length; // allowed
// no setter necessary in this usecase
}
}

无法使用惰性、自动属性或封装在单独的对象中。我考虑过扩展 ObsoleteAttribute,但它是密封的。

最佳答案

这不是你可以开箱即用的事情。您可以编写一个自定义 Roslyn 分析器来检查您的属性并添加警告/错误,但编写 Roslyn 分析器并非易事。请注意,这也不完全困难。

考虑:

// TODO: add an analyzer that checks for this attribute and applies the enforcement
[RestrictAccessTo(nameof(Accessor), nameof(Allowed))]
private string SuperPrivate;

关于c# - 在 C# 中将实例变量的使用限制为单个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65936053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com