简体   繁体   中英

Convert Derived Class to Base Generic Class

I have a set up approximately like this:

public class A { ... }
public class A<T> : A { ... }
public class B<T> : A<T> { ... }
public class C : B<SomeType> { ... }

I am iterating over a list of type A, and I want to check if something is of type B, and if it is, convert it to... B... I can see how it already poses a problem of how am I gonna get the type... but if I cannot do that, what are my other alternatives?

EDIT: To clarify, B contains a method I'd like to use that A does not contain as it simply has no need for it... I want to check which of the objects on that list are of type B so that I can run this method on them

EDIT 2: I forgot to mention the A in the middle earlier... sorry for the confusion

I want to check which of the objects on that list are of type B

Then introduce a type B into your type hierarchy. Currently you don't have a type B , you've got B<SomeType> which is a different type. so

public class A { ... }

public abstract class B : A { ... }

public class B<T> : B { ... }

public class C : B<SomeType> { ... }

Or declare type method you want on an interface

public class A { ... }
public class A<T> : A { ... }
public interface IB
public class B<T> : A<T>, IB { ... }
public class C : B<SomeType> { ... }

Then for any A you can check if it is IB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM