简体   繁体   中英

C# I have an array of superclass objects, which may contain subclass objects. How to test for subclass object & use it's accessors?

I have an Array of AutoMobiles This array may contain SubClass Objects Truck or Car .

How do I test a Position in the Array for the type of Object? eg:

if(AutoMobileArray[1].IsObject(Car)){}

The Car Class has a unique Accessor

public String BootSpace()

How can I use the SubClass Objects Accessors? eg:

if(AutoMobileArray[1].IsObject(Car))
{
    BootSpaceLabel.Text = AutoMobileArray[1].BootSpace();
}
if(AutoMobileArray[1] is Car){ }

is operator: http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.71).aspx

You can then cast to the appropriate type:

if(AutoMobileArray[1] is Car)
{
    Car car = (Car)AutoMobileArray[1];
    BootSpaceLabel.Text = car.BootSpace();
}

Well, If I understand you correctly, there's the is operator:

if(AutoMobileArray[1] is Car)
{
  //Do stuff here
}

To do stuff with the subclass (access methods defined in the subclass etc.) you need to cast:

if(AutoMobileArray[1] is Car)
{
  Car c = (Car)AutoMobileArray[1];
}
Car car = AutoMobileArray[1] as Car;
if(car != null)
{
    BootSpaceLabel.Text = car.BootSpace();
}

You can simply use such expression:

if (AutoMobileArray[1] is Car)
{
    BootSpaceLabel.Text = AutoMobileArray[1].BootSpace();
}

Although there are some workarounds how not to use the "is" keyword, eg you can define method in AutoMobile class like this:

virtual string BootSpace()
{ 
    return string.Empty; 
}

or

abstract string BootSpace();

and override this method in Car subclass (and other subclasses, according to yout business logic):

override string BootSpace()
{
    //Car bootspace logic here 
}

After that you can simply call BootSpaceLabel.Text = AutoMobileArray[1].BootSpace(); without checking object type;

More advanced and "beautiful" way to handle this problem is to use "Design Patterns". There are many standard design problems that are solved effectively. They are known as Design Patterns. In your case the Strategy Pattern might be useful. http://en.wikipedia.org/wiki/Strategy_pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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