简体   繁体   English

派生类-扩展属性

[英]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.... 但是我在myChannel.Path行上收到一条错误消息,说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. 答案很简单:确保您的局部变量的类型为Channel ,因为表达式类型 (通常是变量的类型)决定了成员解析的起点。

As a terse alternative in C# 3: 作为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 . 请注意,这里的myChannel的编译时类型为BaseClass ,因此编译器将无法找到Path属性,因为该属性在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. 如果您坚持实际发布的代码,即使用Channel的编译时类型,那么一切都很好。

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. 如果是这样,则问题在于myChannel是对BaseClass的引用,并且看不到Path属性。

If you need to access Path you can do so with 如果您需要访问路径,可以使用

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

hth, hth,
Alan. 艾伦

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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