铸造父类到子类 [英] Cast parent class to child class

查看:150
本文介绍了铸造父类到子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我已经扩展和增加新的属性Message类。

I have Message class which I have extended and added new property.

class ChildMessage: Message 
{
prop...
}

在试图邮件类添加到ChildMessage名单,我得到了添加的类空引用。

While trying to add Message Class to ChildMessage list I get Null reference for added class.

var myChildList =new List<ChildMessage> ();
var myParentClass = new Message();
myChildList.add(myParentClass as ChildMessage)

myChildList[0] == null //Always return null 

什么是错我的code?有什么办法?

What is wrong with my code? What are the alternatives?

推荐答案

这是因为消息的真实实例不是 ChildMessage ,而 ChildMessage 是消息

It is because a true instance of Message is not a ChildMessage, whereas an instance of ChildMessage is a Message.

除非 myParentClass 终止的实际上的实例化 ChildMessage 你不能用强制转换操作符强制向前塑像作为实际的基础类型是消息

Unless myParentClass is actually instantiated with ChildMessage you cannot use the cast operator to force a forward cast as the actual underlying type is Message.

这是说,有明确投可用于在类型的使用操作符,所以你也许可以创建一个需要消息并输出 ChildMessage

That said, there are implicit and explicit cast operators available for use on types, so you could perhaps create one that takes a Message and outputs a ChildMessage.

<一个href="http://msdn.microsoft.com/en-us/library/85w54y0a.aspx">http://msdn.microsoft.com/en-us/library/85w54y0a.aspx

知道你被赋予这些类型的,你没有选择,只能使用它们,你必须为了延长这种类型的两个选项。

Knowing that you are given these types and you have no choice but to use them, you have two options in order to extend that type.

第一个选项

使用装饰/包装图案包装一个消息 ChildMessage

Use the decorator/wrapper pattern to wrap a Message inside a ChildMessage:

class ChildMessage
{
    private Message _innerMessage;

    public ChildMessage(Message innerMessage)
    {
        _innerMessage = innerMessage;
    }
}

您再暴露无论是消息,或通过 ChildMessage 类的属性。

You then expose either the Message or its properties through the ChildMessage class.

第二个选项

这是同样可行的,从消息,但是当你想使一个 ChildMessage 从继承消息您需要的转换的,而不是将它转换:

This is just as feasible, inherit from the Message, but when you want to make a ChildMessage from a Message you will need to convert it, not cast it:

class ChildMessage : Message
{
    public ChildMessage(Message m)
    {
        // Instantiate properties by copying from m
    }
}

这篇关于铸造父类到子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆