我想知道,在IsNullOrEmpty()
实例(不在.NET Framework中)上使用假设List
方法,如果实例实际上是 null ,它将抛出一个对象引用未设置为对象异常的实例,或类似的东西。考虑到这一点,是否可以在 null 实例上调用方法?
答案 0 :(得分:12)
IsNullOrEmpty()
仅List
String
。在latter的情况下,它是一个静态方法,所以不需要实例,你传入一个字符串引用来检查它,它可以在那里检查null。
答案 1 :(得分:6)
扩展方法可以采用null“this”参数。我不知道框架中的List的任何方法IsNullOrEmpty,但想象它将实现如下:
public bool IsNullOrEmpty<T>(this IList<T> list)
{
if (list == null) return true;
return list.Count == 0;
}
您可以在空引用上调用此(或任何其他)扩展方法,而不会出现任何问题:
List<int> nullList = null;
if (nullList.IsNullOrEmpty())
{
...
}
答案 2 :(得分:3)
AFAIK IsNullOrEmpty
只是类System.String
的一种方法,不适用于List
。它是一种静态方法,而不是扩展方法。你打电话是这样的:
string.IsNullOrEmpty(text);
而不喜欢这个
text.IsNullOrEmpty();
因此,检查引用是否未设置为对象的实例是没有问题的。
答案 3 :(得分:1)
这是一个静态方法,它将有问题的字符串实例作为参数。
public static bool IsNullOrEmpty(
string value
)
http://msdn.microsoft.com/en-us/library/system.string.isnullorempty%28v=vs.110%29.aspx
为IsNullOrEmpty
List
方法
您可以轻松创建扩展方法:
namespace System
{
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string s)
{
return string.IsNullOrEmpty(s);
}
}
}
答案 4 :(得分:1)
正如已经指出的那样,列表没有这种方法。但是很容易编写扩展方法:
public static bool IsNullOrEmpty<T>(this IList<T> list)
{
return (list == null || list.Count == 0);
}
如果要为nulls抛出异常:
public static bool IsEmpty<T>(this IList<T> list)
{
if (list == null)
throw new ArgumentNullException("list");
return (list.Count == 0);
}
答案 5 :(得分:1)
CLR中没有List<T>.IsNullOrEmpty()
。
但是,也许有人为List编写了一个扩展方法。它看起来像这样:
public static class ListExt
{
public static bool IsNullOrEmpty<T>(this List<T> self)
{
return (self == null) || (self.Count == 0);
}
}
如果是这样,您可以从实施中看到,您可以安全地为null
参数传递self
。这个代码会发生这种情况:
List<int> lint = null;
if (lint.IsNullOrEmpty())
{
// ...
这会调用将lint
传递给它的扩展方法;在这种情况下,它会传递null
,并且实施中的(self == null)
检查会导致false
返回,并会阻止任何NullReferenceException
被抛出。
答案 6 :(得分:0)
IsNullOrEmpty()
不支持List
仅适用于String.Following是来自msdn的IsNullOrEmpty
的实际意义。
result = s == null || s == String.Empty;
如果要查看列表,可以编写自己的扩展方法,如下所示。
public static bool IsNullOrEmpty<T>(this ICollection<T> collection)
{
if (collection == null)
return true;
return collection.Count == 0;
}