加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#:解决继承的类及其基础之间的无效的Cast异常

发布时间:2020-12-15 04:00:04 所属栏目:百科 来源:网络整理
导读:我有两个班,名为Post and Question.问题定义为: public class Question : Post{//...} 我的问题类不覆盖任何Post的成员,它只是表达其他一些. 我想完成什么 我有一个类型为Post的对象,其成员已填充.现在,我想把它转换成一个问题,以便我可以为其他几个成员添
我有两个班,名为Post and Question.问题定义为:
public class Question : Post
{
//...
}

我的问题类不覆盖任何Post的成员,它只是表达其他一些.

我想完成什么

我有一个类型为Post的对象,其成员已填充.现在,我想把它转换成一个问题,以便我可以为其他几个成员添加值.

这是我当前的代码,使用一个显式的转换:

Post postToQuestion = new Post();

//Populate the Post...

Question ques = (Question)postToQuestion; //--> this is the error!

//Fill the other parts of the Question.

问题

我得到一个InvalidCastException.我究竟做错了什么?

解决方法

问题是你不能从父母到孩子.您可以为使用父类作为参数的子类创建一个构造函数:
Question 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;
    }
}

但是很明显,C#不允许您使用基类进行隐式转换.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读