简体   繁体   中英

Accessing derived class variable through object of base class in C#

I have code as follows Declare.cs

Class B { }
Class D1 : B { public var1 }
Class D2 : B {}
B Baseobject = new B();
if(baseobject is D1){ Console.print(B.var1) }

When I compile this scenario I always get compiler error that var1 is not accessible to B . If var1 always needs to be in D1 is there way to resolve this?

The object needs to be an instance of D1, so your example is a bit wrong.

You then need to cast your object to D1.

B baseObject = new D1();
Console.WriteLine(((D1)baseObject).var1);

First of all, it won't compile because you need to cast. Why do you need to cast? Because your object reference is a type of B and knows nothing about D1 type and its methods and properties. You need to read a bit more about basic OOP principles

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