c# - 如何将父类引用的子类更改为具有子类的引用类型?

标签 c# inheritance casting reference-type derived-types

我有 20 个左右的事件类,它们都继承自 EventDto。这些子类都被序列化/反序列化(使用DataContractJsonSerializer,每个子类被添加为[KnownType(typeof(subclasstype))]属性),反序列化方法如下所示:

private EventDto DeserializeMessage(byte[] body)
    {
        var stream = new MemoryStream(body);
        var serializer = new DataContractJsonSerializer(typeof(EventDto));

        var eventDto = (EventDto)serializer.ReadObject(stream);

        return eventDto;
    }

反序列化事件后,我需要根据事件的类型对其进行处理。所以我有:

public void ProcessMessage(byte[] serializedEvent)
    {
        //Deserialize
        var eventDto = DeserializeMessage(serializedEvent);

        //Process
        Process(eventDto);
    }

public void Process(EventDto eventDto)
    {
        //Do nothing
    }

    public void Process(EventDtoSubclass1 eventDto)
    {
        //Do something
    }

    public void Process(EventDtoSubclass2 eventDto)
    {
        //Do something different
    }

问题是 ProcessMessage() 中的 eventDto 具有 EventDto 的引用类型,因此调用的 Process() 方法始终相同。我需要能够区分 EventDto 的不同子类并调用适当的方法。

有没有办法将 ProcessMessage() 中的 eventDto 类型从 EventDto 更改为其实际派生类型(例如,EventDtoSubclass2)?

最佳答案

最简单的方法是使用 is 运算符。

public void Process(EventDto eventDto)
{
   //Do nothing
   if (eventDto is EventDtoSubclass1)
   {
       // do something   
   }
   else if (eventDto is EventDtoSubclass2)
   {
       // do something else
   }
}

关于c# - 如何将父类引用的子类更改为具有子类的引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17733204/

相关文章:

c# - 如何正确实例化 HttpContext 对象?

c# - XNA 游戏启动的表单中带有 RichTextBox.ScrollToCaret 的 AccessViolationException

c++ 公历和儒略历继承

ruby-on-rails - Mongoid store_in 产生随机结果

地址的类型转换

c++ - static_cast<int>(foo) 与 (int)foo

c# - 继续我的上一个问题: Having trouble in calculating roots of a quartic equation in C#

c# - 为什么私有(private)字段可以访问而私有(private) setter 不能从静态方法访问?

java - 从父类访问

python - wxPython:动态启用和禁用小部件,从 csv 文件获取设置