简体   繁体   English

如何访问派生类实例的属性,该实例作为参数以基类的形式传递

[英]How to access the properties of an instance of a derived class which is passed as a parameter in the form of the base class

In C# I have a base class and a derived class. 在C#中,我有一个基类和一个派生类。

I have a function which has the base class as an input parameter 我有一个将基类作为输入参数的函数

public void SomeFunction(BaseClass InstanceOfDerivedClass)

Is there a way I can access the properties specific to the derived class, even though it has been passed as a base class? 即使已将其作为基类传递,有没有办法可以访问特定于派生类的属性? Could I use GetType or Cast or something like that? 我可以使用GetType或Cast还是类似的东西?

I appreciate that the solutions may not be elegant but at the moment the alternative is to repeat this function many times for the different derived classes. 我知道解决方案可能并不完美,但目前替代方案是针对不同的派生类多次重复执行此功能。

Casting should definitely do the trick, since the reference in the heap is to that class. 强制转换绝对可以解决问题,因为堆中的引用就是对该类的引用。 Maybe something like: 也许像这样:

if (InstanceOfDerivedClass is DerivedClass)

And in that block you can cast it and interact with it. 在该区块中,您可以投射它并与之交互。

But the bigger question is, why do you need to? 但更大的问题是,您为什么需要? It sounds like this method is using the wrong abstraction if the type being accepted as an argument isn't the correct type. 如果被接受为参数的类型不是正确的类型,听起来这方法使用了错误的抽象。 This is breaking Liskov Substitution and looks like a prime candidate for refactoring the design. 这打破了Liskov替代协议,看起来像是重构设计的主要候选人。 (Of which we don't know enough to help much.) (其中我们所知不足以提供帮助。)

you could do this (bad way): 您可以这样做(糟糕的方式):

public void SomeFunction(BaseClass instanceOfDerivedClass)
{
    DerivedClass derived = null;

    if(instanceOfDerivedClass is DerivedClass)
    {
        derived = instanceOfDerivedClass as DerivedClass;
        // Do stuff like :
        int prop = derived.DerivedProperty;
    }
}

Or, as suggested by Eric (good way): 或者,按照Eric的建议(好的方法):

public void SomeFunction(BaseClass instanceOfDerivedClass)
{
    DerivedClass derived = instanceOfDerivedClass as DerivedClass;

    if(derived != null)
    {
        // Do stuff like :
        int prop = derived.DerivedProperty;
    }
}

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

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