出于性能原因,我试图减少每次调用特定方法时创建引用类型的新实例的开销。
作为一个基本的例子:
public int AccumulativeCount(Expression<Func<int>> exp)
{
// usually do something useful with "exp". Instead put a
// breakpoint and get the memory reference of exp via "&exp"
return 1;
}
当在代码中的其他位置调用它时,AccumulativeCount方法中exp的引用是不同的:
AccumulativeCount(() => 7);
有没有办法让调用代码中的参数静态内联?在上面的示例中,参数&#34;()=&gt; 7&#34;显然永远不会改变,因此没有令人信服的理由为什么每次都应该重新创建它。
我知道我可以将调用代码更改为:
public static Expression<Func<int>> MyStaticCountExp = () => 7;
// ... later in the code
AccumulativeCount(MyStaticCountExp);
我反对上述内容的原因只是表达式才有意义,因为它是一个参数。代码也不尽如人意。是否有类似的东西:
AccumulativeCount(static () => 7); // does not compile
答案 0 :(得分:0)
我不确切知道你的用例,但是Lazy<T>
类可能会有所帮助。
public static readonly Lazy<int> Something = new Lazy<int>(() => AccumulativeCount(() => 7));
public static int AccumulativeCount(Expression<Func<int>> exp) {
// usually do something useful with "exp". Instead put a
// breakpoint and get the memory reference of exp via "&exp"
return 1;
}
public static void DoSomething() {
// the value was not available, so the AccumulativeCount(...) will be called
var a = Something.Value;
// the value is already created, no more call of AccumulativeCount(...) is needed
var b = Something.Value;
var c = Something.Value;
var d = Something.Value;
}