如果一个方法传递了一个Action或Function委托,我不记得我是否真的必须在调用之前制作一个本地副本并测试null ...或者如果已经将它作为一个传入的事实处理了参数? (谷歌现在让我失望了)
如果for循环正在迭代,p_transformer
可以Foo1
为空,而其他一些线程将外部引用置空,需要更像Foo2
的格式,其中本地副本为using System;
using System.Linq;
using System.Collections.Generic;
namespace Extensions
{
public static partial class ExtensionMethods
{
public static IEnumerable<T> foo1<T>(this List<T> p_someList, Func<int, T> p_transformer = null)
{
if (Object.Equals(p_someList, null))
throw new ArgumentNullException("p_someList cannot be null.", default(Exception));
if (p_someList.Count == 0)
throw new ArgumentException("p_someList cannot be empty.");
if (p_transformer != null)
{
for (int i = 0; i < p_someList.Count; i++)
{
p_someList[i] = p_transformer(i);
yield return p_someList[i];
}
}
else
{
for (int i = 0; i < p_someList.Count; i++)
{
yield return p_someList[i];
}
}
}
}
}
代表是第一个?
using System;
using System.Linq;
using System.Collections.Generic;
namespace Extensions
{
public static partial class ExtensionMethods
{
public static IEnumerable<T> foo2<T>(this List<T> p_someList, Func<int, T> p_transformer = null)
{
if (Object.Equals(p_someList, null))
throw new ArgumentNullException("p_someList cannot be null.", default(Exception));
if (p_someList.Count == 0)
throw new ArgumentException("p_someList cannot be empty.");
var Transformer = p_transformer;
if (Transformer != null)
{
for (int i = 0; i < p_someList.Count; i++)
{
p_someList[i] = Transformer(i);
yield return p_someList[i];
}
}
else
{
for (int i = 0; i < p_someList.Count; i++)
{
yield return p_someList[i];
}
}
}
}
}
{{1}}
答案 0 :(得分:4)
您仍然需要检查是否为空。
考虑一下:
private void Caller()
{
Func<int> func = null;
Callee(func);
}
private void Callee(Func<int> func)
{
func(0); // Oops
}
但是,func
函数中的Callee()
参数已经是本地副本。