List <subclass> List <parent class> errors

Source: Internet
Author: User

Record the mistakes made by new users for future reference.

There are two classes

1 public class A2 {3 Public string name {Get; set;} 4} 5 6 public class B: A7 {8 Public int age {Get; set;} 9}

There is a method that requires Class B age as the condition, and finally returns the set of parent Class.

1 public list <A> getabyage (INT age) 2 {3 // method body 4}

In my mind, B is a subclass of A, and you can directly return list <B>, but it doesn't actually work. So I began to find the cause and found that the original idea had a problem.

This is the case. Although a is a subclass of B, the actual types of list <A> and list <B> are both list <t>, A and B are only generic objects of the List <t> object. Therefore, direct return is definitely not feasible. Strong conversion is naturally problematic. How can this problem be solved? The experts told me that the list already provides this conversion method.

For example, if B is an object of the List <B> type, you can use B. Cast <A> (). tolist (); to convert it to a list <A> object.

In addition, I also found that you can write list <A> A = new list <A> (B) In this way. I did not test this method. You can try it. It should also work.

List <subclass> List <parent class> errors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.