简体   繁体   English

动态将派生类类型转换为基类C#

[英]Cast derived class type dynamically to base class type C#

public DerivedClass : BaseClass
{
   // code
}

DerivedClass B = (DerivedClass)MethodReturnsBaseClassObject();
B.DoWork();  

There are many Derived classes being inherited from BaseClass . BaseClass继承了许多Derived类。 So everytime i need to write a new method to use some of the properties. 因此,每次我需要编写一种使用某些属性的新方法。

Is this possible that using reflection we make DerivedClass type dynamic and do something like this and make it generic. 是否有可能使用反射使DerivedClass类型成为动态类型,并执行类似的操作并使它通用。

System.Type type = GetRequestFromSession().GetType();
type B = (type )MethodReturnsBaseClassObject();
Console.WriteLine( B.Name);  
Console.WriteLine( B.Age);  

any help is appreciated. 任何帮助表示赞赏。

You can have safe access to members of the derived type (without casts) while enforcing the base class constraint if you employ a generic method with the following signature: 如果您使用具有以下签名的通用方法,则可以在强制基类约束的同时安全地访问派生类型的成员(不强制转换):

public TDerived MethodReturnsDerivedObject<TDerived>()
    where TDerived : BaseClass

Your calls will then look like this: 您的通话将如下所示:

DerivedClass b = MethodReturnsDerivedObject<DerviedClass>();

b.ExecuteSomeMethodDefinedInBaseClass();

Console.WriteLine(b.SomePropertyDefinedInDerivedClass);  

This feels like bad design to me: you make something generic that you use as something that isn't. 对我来说,这感觉像是糟糕的设计:您将某些通用的东西用作没有的通用东西。 Maybe you should rethink your design. 也许您应该重新考虑您的设计。

For what your question is concerned, maybe you can create a proxy method or class that returns the type you expect. 对于您的问题,也许您可​​以创建一个返回所需类型的代理方法或类。 This is only useful when there is a low number of methods you call. 这仅在您调用的方法数量较少时才有用。

Another option is to use the dynamic keyword, but I would advice only to use that if nothing else works. 另一种选择是使用dynamic关键字,但是我建议仅在没有其他效果的情况下使用它。

I would go with Kirill Shlenskiy's answer for now. 我现在会同意Kirill Shlenskiy的回答。 But I'd also like to suggest moving this method onto the base class itself if it makes sense to do so . 但是我也建议如果可行的话,将此方法移至基类本身。 There may be tangled dependencies or other weirdness that prohibits this solution, but it may also allow you to have one consumer without using generics. 可能存在缠结的依存关系或其他怪异现象阻止了此解决方案,但它也可能使您可以拥有一个使用者而不使用泛型。

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

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