假設空值和空集合是等價的,我試圖編寫IEnumerable類型的擴展方法來返回派生類型的空集合而不是null。通過這種方式,我不必在所有地方重複執行空值檢查,並且我不會收到必須投出的IEnumerable。C#EmptyIfNull擴展任何IEnumerable返回空派生類型
例如
List<Foo> MethodReturningFooList()
{
...
}
Foo[] MethodReturningFooArray()
{
...
}
void Bar()
{
List<Foo> list = MethodReturningFooList().EmptyIfNull();
Foo[] arr = MethodReturningFooArray().EmptyIfNull();
}
public static class Extension
{
public static T EmptyIfNull<T>(this T iEnumerable)
where T : IEnumerable, new()
{
var newTypeFunc = Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile();
return iEnumerable == null ? newTypeFunc() : iEnumerable;
}
}
此擴展似乎工作,但沒有人看到任何陷阱?
Returnin默認() – Totodile
IEnumerable和IEnumerable的是不一樣的東西。 –
每次調用'EmptyIfNull'時,都會編譯一個新方法。你可以簡單地執行'return iEnumerable == null? Activator.CreateInstance():iEnumerable;' –
Rob