Max*_*sky 10 .net c# oop inheritance casting
我有两个名为Post和Question的课程.问题定义为:
public class Question : Post
{
//...
}
Run Code Online (Sandbox Code Playgroud)
我的问题类没有覆盖Post的任何成员,它只是表达了一些其他成员.
我有一个Post类型的对象,其成员已填充.现在,我想将其转换为一个问题,以便我可以为少数其他成员添加值.
这是我当前的代码,使用显式强制转换:
Post postToQuestion = new Post();
//Populate the Post...
Question ques = (Question)postToQuestion; //--> this is the error!
//Fill the other parts of the Question.
Run Code Online (Sandbox Code Playgroud)
我收到了InvalidCastException.我究竟做错了什么?
Joe*_*oel 22
问题是您无法从父级转换为子级.您可以为子类创建一个构造函数,将父类作为参数:问题ques = new Question(myPost);
您还可以使用隐式运算符使其变得简单:问题ques = myPost;
http://www.codeproject.com/KB/cs/Csharp_implicit_operator.aspx
编辑:实际上,我只是尝试输入一个演示,为你做隐式运算符:
class Question : Post
{
public Question()
{
//...
}
public Question(Post p)
{
// copy stuff to 'this'
}
public static implicit operator Question(Post p)
{
Question q = new Question(p);
return q;
}
}
Run Code Online (Sandbox Code Playgroud)
但是通常C#不允许你用基类进行隐式转换.
此时发布不是问题,CLR正在抱怨.你可以将问题转发给Post,但不是反之亦然.现在,如果你对一个你知道是一个问题的帖子有一个高级别的引用,你可以这样下转:
public Post Post
{
set
{
if (value is Question)
{
question = (Question)value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但即使这是代码味道.
但是我认为你想要实现的目标可以在没有类型转换的情况下实现,或者根本没有继承.遵循古老的"赞成封装继承"原则,为什么不将Post对象包装到您的Question对象中,例如:
public class Question
{
Post post;
public Question(Post post)
{
this.post = post;
}
}
Run Code Online (Sandbox Code Playgroud)
假设您已经为Post的相关成员定义了属性,而不是
Question ques = (Question)post;
Run Code Online (Sandbox Code Playgroud)
你有
Question ques = new Question(post);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24054 次 |
最近记录: |