首页 > 解决方案 > C# 中的条件变量作用域

问题描述

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

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

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

例子:

仅当属性为时,属性B才适用。如果用户设置为,则当前范围将失去 的可见性。AtrueAfalseB

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

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

标签: c#design-patternsscopeconditionalvisibility

解决方案


您不能完全按照您的要求进行操作,但是您可以通过构建器模式获得紧密链接流利 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()。我没有为建设者提供 impls,但应该很容易弄清楚。让我知道您是否需要除构建器示例之外的其他东西,例如https://www.dofactory.com/net/builder-design-pattern

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


推荐阅读