簡體   English   中英

C#我有一個超類對象數組,其中可能包含子類對象。 如何測試子類對象並使用它的訪問器?

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

我有一個AutoMobiles Array 。此數組可能包含SubClass Objects TruckCar

如何測試對象類型在數組中的位置? 例如:

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

Car類具有唯一的訪問器

public String BootSpace()

如何使用子類對象訪問器? 例如:

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

is運算符: http : //msdn.microsoft.com/zh-cn/library/scekt9xw(v=vs.71).aspx

然后可以將其強制轉換為適當的類型:

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

好吧,如果我理解正確的話,那就是is運算符:

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

要處理子類(在子類中定義的訪問方法等),您需要強制轉換:

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

您可以簡單地使用以下表達式:

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

盡管有一些解決方法如何不使用“ is”關鍵字,例如,您可以在AutoMobile類中定義如下方法:

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

要么

abstract string BootSpace();

並在Car子類(和其他子類,根據您的業務邏輯)中override此方法:

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

之后,您可以簡單地調用BootSpaceLabel.Text = AutoMobileArray[1].BootSpace(); 不檢查對象類型;

處理此問題的更高級且“美觀”的方法是使用“設計模式”。 有許多有效解決的標准設計問題。 它們被稱為設計模式。 在您的情況下,策略模式可能會有用。 http://en.wikipedia.org/wiki/Strategy_pattern

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM