简体   繁体   中英

Derived class - extending properties

i am still learning and fighting derived classes.

tried something simple ( from the examples i have seen all over ):

public class BaseClass
{
    public string Title {get;set;}
}

public class Channel : BaseClass
{
    public string Path { get; set; }
}


Channel myChannel = new Channel();
myChannel.Title = "hello";
myChannel.Path = "123";

but i get an error on the myChannel.Path line saying BaseClass does not contain a definition for Path and no extension....

help me please, what am i doing wrong?

The example you show is fine. I think in your actual code you have:

BaseClass myChannel = new Channel();
myChannel.Title = "hello";
myChannel.Path = "123";

so the answer is simply: ensure your local variable is typed as Channel , since it is the the expression type (typically: the type of a variable) that determines the starting point for member resolution.

As a terse alternative in C# 3:

var myChannel = new Channel { Title = "hello", Path = "123" };

The code you've given compiles fine. I suspect you've actually got code like this:

BaseClass myChannel = new Channel();
myChannel.Title = "hello";
myChannel.Path = "123";

Note that here, the compile-time type of myChannel is BaseClass - so the compiler wouldn't be able to find the Path property, as it's not present in BaseClass . The compiler can only find members based on the compile-time type of the variable. (Leaving dynamic typing aside...)

If you stick to the code you actually posted, ie with a compile-time type of Channel , then all should be fine.

The code as written runs fine. What I suspect you have is

BaseClass myChannel = new Channel()

If so, the problem is that myChannel is a reference to a BaseClass and cannot see the Path property.

If you need to access Path you can do so with

(myChannel as Channel).Path = "123";

hth,
Alan.

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