【发布时间】:2021-02-07 20:32:28
【问题描述】:
我有一个函数,它接受一个 Func
函数的返回值在调用 TryFindValue 之间可能会发生变化,但在迭代列表时它们不会发生变化。我想避免产生垃圾(例如通过转换为对象来装箱/拆箱)。理想情况下,我只需要将空间用于 TryFindValue 范围内的记忆值,而不是例如每个委托的整个生命周期,但我不知道这是否可能。
public class SomeClass
{
public bool TryFindValue(List<CondValue> list, out int value)
{
for (int i = 0; i < list.Count; i++)
{
var condValue = list[i];
if (condValue.cond())
{
value = condValue.value;
return true;
}
}
value = default(int);
return false;
}
}
public class SomeOtherClass
{
private List<CondValue> list;
public SomeOtherClass()
{
list = new List<CondValue>();
// SomeMethod(3) will be calculated twice
list.Add(new CondValue(() => SomeMethod(3) > SomeOtherMethod(), 42));
list.Add(new CondValue(() => SomeMethod(3) < SomeThirdMethod(), 35));
}
private float SomeMethod(int value)
{
// Implementation... (uses some internal or global state)
}
private int SomeOtherMethod()
{
// Implementation... (uses some internal or global state)
}
private int SomeThirdMethod()
{
// Implementation... (uses some internal or global state)
}
}
public struct CondValue
{
public Func<bool> cond;
public int value;
public CondValue(Func<bool> func, int value)
{
this.func = func;
this.value = value;
}
}
【问题讨论】:
-
给委托添加上下文参数,带字典?
标签: c# delegates memoization