3
4

3 回答 3

6

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

    }
}
于 2010-05-20T12:17:21.720 回答
5

IEnumerable<object>不是 的超类型IEnumerable<T>,因此它也不是List<T>两者的超类型。请参阅问题 2575363以简要了解为什么会出现这种情况(它与 Java 有关,但概念是相同的)。顺便说一句,这个问题已经在 C# 4.0 中解决了,它支持协变泛型

您没有发现此错误的原因是因为您使用x as T了 ,您应该一直在使用普通强制转换 ( (T)x),请参阅问题 2139798。结果InvalidCastException会指出你的错误。(事实上​​,如果类型关系是正确的(即如果IEnumerable<object>是 的超类型List<T>),则根本不需要强制转换。)

要解决您的问题,请使您的方法通用,以便它接受 aIEnumerable<T>而不是 a IEnumerable<object>,并完全跳过强制转换。

 public static void VerifyNotNullOrEmpty<T>(IEnumerable<T> theIEnumerable,
                                            string theIEnumerableName,
                                            string theVerifyingPosition) { ... }
于 2010-05-20T12:32:21.333 回答
4

假设您的目标至少是 framework 3.0:

IEnumerable<object>使用扩展转换为泛型:

var myEnumerable = myList.Cast<object>();

编辑:无论如何,我建议您更改方法以获得纯 IEnumerable,例如:

public static void VerifyNotNullOrEmpty(IEnumerable theIEnumerable,
                                        string theIEnumerableName,
                                        string theVerifyingPosition)

并在方法内部使用 foreach 或检查是否为空theIEnumerable.Cast<object>().Count()

这样你就不必每次都投射到IEnumerable<object>

于 2010-05-20T12:10:15.223 回答