![](/img/trans.png)
[英]How to access to the properties of List<T>, where T is a different object every time
[英]How to reference properties in an object to reevaluate them every time
我嘗試使用字典將一些enum
映射到許多bool
屬性:
private Dictionary<FooEnum, bool> isBarByFoo;
private Dictionary<FooEnum, bool> IsBarByFoo
{
get
{
return isBarByFoo ?? (isBarByFoo = new Dictionary<FooEnum, bool>
{
{ FooEnum.Foo1, IsBar1 },
{ FooEnum.Foo2, IsBar2 },
{ FooEnum.Foo3, IsBar3 }
});
}
}
private bool IsBar1 => SomeConditionsThatChangeOverRuntime1();
private bool IsBar2 => SomeConditionsThatChangeOverRuntime2();
private bool IsBar3 => SomeConditionsThatChangeOverRuntime3();
但是,這種方法行不通,因為創建字典並將其保存為值類型時僅對屬性進行一次評估,結果我誤解了屬性的工作方式。
是否可以將屬性存儲在字典中,從而在每次查找屬性時對其進行評估,或者您可以針對這種問題提出不同的解決方案嗎?
關於什么:
private Dictionary<FooEnum, Func<bool>> isBarByFoo;
private Dictionary<FooEnum, Func<bool>> IsBarByFoo
{
get
{
return isBarByFoo ?? (isBarByFoo = new Dictionary<FooEnum, Func<bool>>
{
{ FooEnum.Foo1, SomeConditionsThatChangeOverRuntime1},
{ FooEnum.Foo2, SomeConditionsThatChangeOverRuntime2},
{ FooEnum.Foo3, SomeConditionsThatChangeOverRuntime3}
});
}
}
private bool SomeConditionsThatChangeOverRuntime1() => true;
private bool SomeConditionsThatChangeOverRuntime2() => false;
private bool SomeConditionsThatChangeOverRuntime3() => true;
當您通過IsBarByFoo[FooEnum.Foo1]()
獲得字典的值時,您將獲得所需的值
另一個解決方案可能是忘記字典,而只是使用一種方法來獲取值:
private bool GetIsBarByFoo(FooEnum foo)
{
switch (foo)
{
case FooEnum.Foo1:
return SomeConditionsThatChangeOverRuntime1();
case FooEnum.Foo2:
return SomeConditionsThatChangeOverRuntime2();
case FooEnum.Foo3:
return SomeConditionsThatChangeOverRuntime3();
default:
return false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.