Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

c# - Casting of Generic List to a Class derived from a List

I created a class derived from List. However when I tried casting the class to another List object I get a runtime error. My code is similar to the one posted below:

public class CategoryObj
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
}

public class CategoryObjCollection:List<CategoryObj>
{

}

public void Test()
{
        CategoryObjCollection cat = new CategoryObjCollection();
        using (NWDataContext db = new NWDataContext())
        {
            var qry = (from c in db.Categories
                       select new CategoryObj
                       {
                           CategoryID = c.CategoryID,
                           CategoryName = c.CategoryName,
                           Description = c.Description
                       }).ToList();
            cat = (CategoryObjCollection)qry; //runtime error Unable to cast object of type 'System.Collections.Generic.List`1[WindowsFormsApplication1.CategoryObj]' to type 'WindowsFormsApplication1.CategoryObjCollection'.
        }
}

I hope someone can help me on this. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why would you expect to be able to cast? The object isn't an instance of CategoryObjCollection. The point of reference type casts (when they're actually casting rather than invoking explicit conversions) is to tell the compiler that you believe the execution time type of the object is actually compatible with the type you specify, so that you can use members of that specific type (after the execution time test). In this case, the ToList extension method just creates a new List<T>.

More to the point, what is your CategoryObjCollection type meant to achieve in the first place? If it has any state other than the normal list, where would you expect that state to come from after your LINQ query? If it doesn't have any other state, is it really adding any benefit? Maybe your type should actually contain a list rather than deriving from it? Then you could create a new instance of the type using the results of the query.

In general, it's usually a design smell to derive from List<T>. It doesn't provide many ways to specialize its "listiness" (unlike, say, Collection<T>). It's usually a sign that you should be thinking of composition instead of inheritance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...