c# - C# 中的条件变量作用域
问题描述
所以这是一个奇怪的问题,有没有办法根据特定条件(例如通过某些属性)修改变量的可见性?
这可能更像是一个设计模式问题,所以请允许我解释一下我的情况:
我有一个具有许多用户可配置值的类(总共 9 个,其中 4 个是有条件的)。但是,其中一些变量仅在满足某些条件时才适用。现在,它们对用户都是可见的。我正在寻找一种方法可以在每个范围的上下文中在编译时限制某些变量的可见性。我想避免让用户感到困惑,并让他们可能设置某些会被忽略的值。
例子:
仅当属性为时,属性B
才适用。如果用户设置为,则当前范围将失去 的可见性。A
true
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()
。我没有为建设者提供 impls,但应该很容易弄清楚。让我知道您是否需要除构建器示例之外的其他东西,例如https://www.dofactory.com/net/builder-design-pattern。
这是一个简单的例子:https ://dotnetfiddle.net/DtEidh
推荐阅读
- c# - Visual Studio 正在尝试从与 .csproj.user 中指定的路径不同的路径运行应用程序
- javascript - 用于追求最大值的 Javascript
- jquery - Html:根据第一个选择器过滤第二个选择器
- java - 连接到 sql server 的 JDBC 问题
- json - 如何使用 Laravel API 功能返回第一个 json 元素?
- java - GSON - 从 JSON 对象中删除 JSON 数据
- kubernetes - Kubernetes 仪表板在使用代理时给出“未经授权”
- git - 为什么我在 osxkeychain 中找不到 git 密码?
- perl - 使用 Perl 的 Soap::Lite 调用简单的 Soap API
- grails - 如何绑定到sqldate?