简体   繁体   English

将派生类转换为基泛型类

[英]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?我正在遍历 A 类型的列表,我想检查某物是否属于 B 类型,如果是,则将其转换为...... B...... 我可以看到它已经提出了我的问题会得到类型...但如果我不能那样做,我还有什么其他选择?

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编辑:为了澄清,B 包含一个我想使用的方法,但 A 不包含它,因为它根本不需要它......我想检查该列表中的哪些对象是 B 类型的,以便我可以在他们身上运行这个方法

EDIT 2: I forgot to mention the A in the middle earlier... sorry for the confusion编辑 2:我之前忘了在中间提到 A ......抱歉造成混淆

I want to check which of the objects on that list are of type B我想检查该列表中的哪些对象属于 B 类型

Then introduce a type B into your type hierarchy.然后将类型 B 引入到您的类型层次结构中。 Currently you don't have a type B , you've got B<SomeType> which is a different type.目前你没有类型B ,你有B<SomeType> ,这是一种不同的类型。 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然后对于任何 A 你可以检查它is IB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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