C#中的条件变量范围

时间:2018-07-18 01:10:15

标签: c# design-patterns scope conditional 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(); }

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

2 个答案:

答案 0 :(得分:2)

您不能完全 ,但可以使用构建器模式将流利的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
}

请注意,吸气剂仅在ISettings中定义,最好使该类不可变,以免在被Build()后更改。我没有为建造者提供提示,但应该足够容易找出。让我知道您是否确实需要构建器示例以外的内容,例如https://www.dofactory.com/net/builder-design-pattern

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

答案 1 :(得分:0)

否,这是不可能的。如果是某种安全性问题,请注意,如果您想发疯,甚至可以将internal事物称为via reflection

我能想到的最接近的接口:

public interface IA
{
    public bool A { get; set; }
}

public interface IB
{
    public bool B { get; set; }
}

public class Settings: IA, IB
{
    public bool A { get; set; }
    public bool B { get; set; }
}

用法例如:

IA config = new Settings();
config.A = true; //fine
config.B = true; //error

也就是说,如果有问题,您的模型可能包含很多数据。也许AB可以是单独的类,它们是模型的属性?

public class Settings
{
    public A A {get; set;}
    public B B {get; set;}
}

或者您可以创建一个工厂类

public class SettingsFactory
{
    public Settings CreateA(...)
    {
        return new Settings { ... };
    }

    public Settings CreateB(...)
    {
        return new Settings { ... };
    }
}

无论如何,您应该信任您的用户,他正在阅读您的文档。