List 实现了 IEnumerable 所以你不需要强制转换它们,你只需要让它让你的方法接受一个泛型参数,就像这样:
public static void VerifyNotNullOrEmpty<T>(this IEnumerable<T> theIEnumerable,
string theIEnumerableName,
string theVerifyingPosition)
{
string errMsg = theVerifyingPosition + " " + theIEnumerableName;
if (theIEnumerable == null)
{
errMsg += @" is null";
Debug.Assert(false);
throw new ApplicationException(errMsg);
}
else if (theIEnumerable.Count() == 0)
{
errMsg += @" is empty";
Debug.Assert(false);
throw new ApplicationException(errMsg);
}
}
您应该可以通过以下方式调用它:
var myList = new List<string>
{
"Test1",
"Test2"
};
myList.VerifyNotNullOrEmpty("myList", "My position");
您还可以稍微改进实现:
public static void VerifyNotNullOrEmpty<T>(this IEnumerable<T> items,
string name,
string verifyingPosition)
{
if (items== null)
{
Debug.Assert(false);
throw new NullReferenceException(string.Format("{0} {1} is null.", verifyingPosition, name));
}
else if ( !items.Any() )
{
Debug.Assert(false);
// you probably want to use a better (custom?) exception than this - EmptyEnumerableException or similar?
throw new ApplicationException(string.Format("{0} {1} is empty.", verifyingPosition, name));
}
}