我有以下扩展方法来帮助我检查和实例化对象是否为空。前两个工作得很好,但它们不是很有用。
public static bool IsNull<T>(this T t)
{
return ReferenceEquals(t, null);
}
public static T NewIfNull<T>(this T t, Func<T> createNew)
{
if (t.IsNull<T>())
{
return createNew();
}
return t;
}
public static void Ensure<T>(this T t, Func<T> createNew)
{
t = t.NewIfNull<T>(createNew);
}
最终我想做类似的事情
IList<string> foo;
...
foo.Ensure<IList<string>>(() => new List<string>());
然而, Ensure 方法并没有达到预期的效果,即设置foo
为List<string>
if 它为 null 的实例,否则基本上将其设置为自身。
如果您现在知道我可以调整 Ensure 方法来实现这一点,我将不胜感激。
谢谢,汤姆