派生类 - 扩展属性
我还在学习和战斗派生类。
尝试了一些简单的事情(从我见过的所有示例中):
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";
但是我在 myChannel.Path 行上收到错误,指出 BaseClass 不包含 Path 的定义并且没有扩展名... .
请帮帮我,我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你展示的例子很好。我认为在您的实际代码中您有:
所以答案很简单:确保您的局部变量的类型为
Channel
,因为它是表达式类型(通常:类型变量)确定成员解析的起点。作为 C# 3 中的简洁替代方案:
The example you show is fine. I think in your actual code you have:
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:
您给出的代码编译得很好。我怀疑您实际上有这样的代码:
请注意,这里,
myChannel
的编译时类型是BaseClass
- 所以编译器不会无法找到Path
属性,因为它不存在于BaseClass
中。编译器只能根据变量的编译时类型来查找成员。 (将动态类型放在一边...)如果您坚持实际发布的代码,即使用
Channel
的编译时类型,那么一切都应该没问题。The code you've given compiles fine. I suspect you've actually got code like this:
Note that here, the compile-time type of
myChannel
isBaseClass
- so the compiler wouldn't be able to find thePath
property, as it's not present inBaseClass
. 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, i.e. with a compile-time type of
Channel
, then all should be fine.编写的代码运行良好。我怀疑你的情况是
如果是这样,问题是 myChannel 是对 BaseClass 的引用,并且无法看到 Path 属性。
如果您需要访问 Path,您可以使用
hth,
艾伦.
The code as written runs fine. What I suspect you have is
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
hth,
Alan.