所以这是一个奇怪的问题,有没有办法根据特定条件(例如通过某些属性)修改变量的可见性?
这可能更多是一个设计模式问题,所以请允许我解释一下我的情况:
我有一个类,其中有许多用户可配置的值(总共 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()
后不允许更改。我没有为构建者提供实现,但应该很容易弄清楚。如果您确实需要除构建器示例之外的其他内容,请告诉我,例如 https://www.dofactory.com/net/builder-design-pattern .
这是一个简单的示例:https://dotnetfiddle.net/DtEidh
关于c# - C# 中的条件变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392145/