gpt4 book ai didi

c# - 通用列表 作为 IEnumerable
转载 作者:行者123 更新时间:2023-11-30 13:18:11 24 4
gpt4 key购买 nike

我正在尝试将 List 转换为 IEnumerable,因此我可以验证不同的列表不为 null 或为空:

假设 myList 是一个 List 。然后在我想要的调用者代码中:

       Validator.VerifyNotNullOrEmpty(myList as IEnumerable<object>,
@"myList",
@"ClassName.MethodName");

验证代码为:

     public static void VerifyNotNullOrEmpty(IEnumerable<object> 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);

}
}

但是,这是行不通的。它编译,但 IEnumerable 为空!为什么?

最佳答案

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));

}
}

关于c# - 通用列表<T> 作为 IEnumerable<object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2873480/

24 4 0