简体   繁体   中英

C# Can't access base properties of a class (only inherited)

Here is my code (should be easy to understand what I'm trying to achieve):

public class Order
{
    private Drink drink;
    public Drink Drink {get { return drink; } set { drink = value; }}
}

public class Drink
{
    enum colour 
    {
        Red, Transparent
    };
}

public class cocktail : Drink
{
    private int alcoholContent;
    public int AlcoholContent  { get { return alcoholContent; } set { alcoholContent = value; } }
}

And then I'm trying to access the properties, but they aren't there:

Order order = new Order();
order.Drink = new cocktail();
order.Drink. <- no alcohol content?

Why is that? I thought I did create a cocktail class, not just a Drink? What am I doing wrong?

Thank you!

You can't use AlcoholContent property directly, because you're using Coctail instance through Drink reference.

Order order = new Order();
order.Drink = new cocktail();
//  order.Drink. <- no alcohol content?
((Coctail)order.Drink).AlcoholContent <- works just fine

You have to use explicit (Coctail) cast to use members specific to Coctail class.

Why is that? Consider a situation, where there is another class named SoftDrink :

public class SoftDrink : Drink
{
}

You'd still be able to assign SoftDrink instance to order.Drink :

Order order = new Order();
order.Drink = new SoftDrink();
//  order.Drink. <- no alcohol content? It's a SoftDring!!

And because order.Drink property can handle every Drink , you can only use members specified for Drink class. Even if there is really a more specific class instance assigned to that property.

You need to distinguish between the actual type and the declared type. In your case, although you instantiate a cocktail , you are referencing it as a Drink , which does not expose any properties.

To access the properties defined in the cocktail class, you need to type-cast your reference:

((cocktail)order.Drink).AlcoholContent = 4;

If you want to get concrete class properties then should have to explicitly cast to concrete type.

(order.Drink as Cocktail).AlcoholC ontent <- works just fine

Or

You can keep a virtual property as Alcoholicontent in Drink class and override it in cocktail class. Then you can access those properties.

You can cast it. Try:

Order order = new Order();
order.Drink = new cocktail();
(order.Drink as cocktail).AlcoholContent = 0 ; // please dont drink

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