简体   繁体   English

转换一个泛型类,它是一个对象的类型

[英]Casting a generic class which is an object to it's type

This is a class hierarchy question related to generics. 这是与泛型相关的类层次结构问题。 I have a mostly derived class MyClass3<T> which is derived from MyClass2<T> . 我有一个主要派生类MyClass3<T> ,它派生自MyClass2<T> The class MyClass2<T> has a property called MyProperty . MyClass2<T>类有一个名为MyProperty的属性。

I have a method VerifyMyProperty which accepts an object of type MyClass3. 我有一个方法VerifyMyProperty接受MyClass3类型的对象。 Since it is generic, it can be MyClass3<A> or MyClass3<B> or MyClass3<C> . 由于它是通用的,它可以是MyClass3<A> or MyClass3<B> or MyClass3<C>

My question is, how can I cast MyClass3 to MyClass2 to check the property MyProperty ? 我的问题是,如何将MyClass3转换为MyClass2以检查属性MyProperty Without generics, it would be easy as var myClass2 = anyofMyClass as MyClass2 . 如果没有泛型,那么var myClass2 = anyofMyClass as MyClass2 With generics where the T can be A, B or C, how can I do the same casting? 对于T可以是A,B或C的泛型,我该如何进行相同的投射?

public class MyClass3<T> : MyClass2<T>
{
....
}

public class MyClass2<T> : MyClass1
{
    T MyProperty { get; private set; }
}

public void VerifyMyProperty(object anyofMyClass)
{
    var myClass2 = anyofMyClass as MyClass2; // Finding the MyClass2. This line will return a compiler error.

    if (myClass2.MyProperty != null)
    {
       Console.Writeline("MyClass2.MYProperty is not null.");
    }
}

First of all: In your example MyClass2 does not exists. 首先:在您的示例中, MyClass2不存在。 Only MyClass<T> is a valid class. 只有MyClass<T>是一个有效的类。

So you might consider: 所以你可能会考虑:

var myClass2 = anyofMyClass as MyClass2<T>;

In case anyOfMyClass must be able to contain a MyClass2 with another generic type, something goes wrong. 如果anyOfMyClass必须能够包含另一个泛型类型的MyClass2,那么就会出错。

You might want to consider an implementation of a common and general interface with a property like: 您可能希望考虑使用以下属性的公共和通用接口的实现:

interface IMyInterface
{
    object MyProperty { get; }
}

public class MyClass2<T> : MyClass1, IMyInterface
{
    T MyProperty { get; private set; }
    object IMyInterface.MyProperty { get { return MyProperty; }}
}

When you implement this interface explicitly (see: http://msdn.microsoft.com/en-us/library/aa664591(v=vs.71).aspx ), you could solve your problem in the non-generic way: 当您明确实现此接口时(请参阅: http//msdn.microsoft.com/en-us/library/aa664591 (v = vs.71.aspx ),您可以通过非泛型方式解决问题:

var myClass2 = anyofMyClass as IMyInterface;
if (myClass2.MyProperty != null)
    ...

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

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