c# - C# 中的条件变量作用域

标签 c# design-patterns scope conditional-statements visibility

所以这是一个奇怪的问题,有没有办法根据特定条件(例如通过某些属性)修改变量的可见性?

这可能更多是一个设计模式问题,所以请允许我解释一下我的情况:

我有一个类,其中有许多用户可配置的值(总共 9 个,其中 4 个是有条件的)。然而,其中一些变量仅在满足某些条件时才适用。现在,它们对用户都是可见的。我正在寻找一种可以在编译时在每个范围上下文中限制某些变量的可见性的方法。我想避免让用户感到困惑并让他们可能设置某些会被忽略的值。

示例:

属性B仅在属性Atrue时适用。如果用户将 A 设置为 false,则当前作用域将失去 B 的可见性。

var settings = new Settings() {
    A = true,
    B = ... //Everything is fine since A is true
}


var settings = new Settings() {
    A = false,
    B = ... //Compile Error, Settings does not contain definition for "B"
}

//Somewhere that uses the settings variable...
if(A) { useB(B); } else { useDefault(); }

有比“良好的文档”更好的解决方案吗?

最佳答案

您无法完全执行您所要求的操作,但您可以通过构建器模式获得紧密链接流畅 API 的功能...

public interface ISettings
{
    string SomePropertyOnlyForTrue { get; }
    int B { get; }
}

public interface IBuilderFoo
{
    IBuilderFooTrue BuildFooTrue();
    IBuilderFooFalse BuildFooFalse();
}

public interface IBuilderFooTrue
{
    IBuilderFooTrue WithSomePropertyOnlyForTrue(string value);
    ISettings Build();
}

public interface IBuilderFooFalse
{
    IBuilderFooFalse WithB(int value);
    ISettings Build();
}

public void Whatever()
{
    var theThingTrue = new BuilderFoo().BuildFooTrue()
        .WithSomePropertyOnlyForTrue("face").Build();
    var theThingTrueCompilerError = new BuilderFoo().BuildFooTrue()
        .WithB(5).Build(); // compiler error

    var theThingFalse = new BuilderFoo().BuildFooFalse()
        .WithB(5).Build();
    var theThingFalseCompilerError = new BuilderFoo().BuildFooFalse()
        .WithSomePropertyOnlyForTrue("face").Build(); // compiler error
}

请注意,getter 仅在 ISettings 中定义,您最好使类不可变,以便在 Build() 后不允许更改。我没有为构建者提供实现,但应该很容易弄清楚。如果您确实需要除构建器示例之外的其他内容,请告诉我,例如 https://www.dofactory.com/net/builder-design-pattern .

这是一个简单的示例:https://dotnetfiddle.net/DtEidh

关于c# - C# 中的条件变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392145/

相关文章:

javascript - 全局变量未分配给函数外部。

c# - .NET ReactiveExtension 观察器未捕获 OnError 中的错误

java - 什么时候使用 instanceof 才是正确的决定?

javascript - js 脚本可以获取在同一文件内的 EJS 上下文/页面中写入的变量吗

c - C 中的指针持久性?

c# - 多种服务的WCF服务架构

c# - 从 Windows 服务处理长时间运行的操作

c# - IEnumerable 和 IEnumerable<T> 之间的区别?

c# - WPF 在 XAML 上获取类实例空引用

python - 在 pydantic 模型中包含非验证方法是不好的做法吗?