如何访问派生类实例的属性,该派生类作为参数以基类的形式传递 [英] 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
问题描述
在C#中,我有一个基类和一个派生类.
In C# I have a base class and a derived class.
我有一个将基类作为输入参数的函数
I have a function which has the base class as an input parameter
public void SomeFunction(BaseClass InstanceOfDerivedClass)
是否有一种方法可以访问特定于派生类的属性,即使它已经作为基类传递了呢?我可以使用GetType或Cast还是类似的东西?
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?
我意识到解决方案可能并不完美,但目前,替代方法是针对不同的派生类多次重复执行此功能.
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.
推荐答案
您可以这样做(不好的方式):
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;
}
}
或者,按照埃里克(Eric)的建议(好的方法):
Or, as suggested by Eric (good way):
public void SomeFunction(BaseClass instanceOfDerivedClass)
{
DerivedClass derived = instanceOfDerivedClass as DerivedClass;
if(derived != null)
{
// Do stuff like :
int prop = derived.DerivedProperty;
}
}
这篇关于如何访问派生类实例的属性,该派生类作为参数以基类的形式传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!