我想要一個列舉欄位,如果它不為 null 或取決于另一個成員值,它可以設定為其自己的值。
我正在嘗試做這樣的事情:
public class Test {
public bool Foo { get; set; } = false;
public TypeEnum Bar {
set
{
Bar = Bar ?? (Foo ? TypeEnum.Type1 : TypeEnum.Type2);
}
}
}
uj5u.com熱心網友回復:
我認為 Jeroen 在評論中提出的建議是:
public class Test
{
public bool Foo { get; set; } = false;
public TypeEnum? Bar { get; private set; }
public void SetBarDependingOnFoo()
{
Bar = Bar ?? (Foo ? TypeEnum.Type1 : TypeEnum.Type2);
}
}
不過,那將是一次性設定,因為一旦它不再存在,它就會保留該值null。
當然,您可以在 上撰寫一個自定義設定器Foo,重置Bar為null... 但現在我正在猜測您想要什么。
另一種方法會有點不同,行為會有所不同:
public class Test
{
public bool Foo { get; set; } = false;
public TypeEnum Bar => Foo ? TypeEnum.Type1 : TypeEnum.Type2;
}
在這里, 的值Bar 總是取決于 的當前狀態Foo。
假設 Foo 在設定后不能靜音。
在那種情況下,我會質疑這門課是否真的有意義。你可能想要更多的“建設者”......
public interface IBarBuilder
{
IBarBuilder WithFoo(bool foo);
TypeEnum Build();
}
public class BarBuilder: IBarBuilder
{
private bool _myFoo = false;
IBarBuilder IBarBuilder.WithFoo(bool foo)
{
_myFoo = foo;
return this;
}
TypeEnum IBarBuilder.Build()
{
return _myFoo ? TypeEnum.Type1 : TypeEnum.Type2;
}
}
用法
var builder = new BarBuilder().WithFoo(true);
TypeEnum myBar = builder.Build(); // from here use myBar
或者更簡單(我假設您的實際用例可能更復雜):工廠方法(“工廠”在這里有點夸張):
public static TypeEnum GetBar(bool foo) => foo ? TypeEnum.Type1 : TypeEnum.Type2;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/534465.html
標籤:C#应用程序接口
下一篇:無法使用不記名令牌獲取資料
