当前位置:  开发笔记 > 编程语言 > 正文

向派生类添加不同的属性#

如何解决《向派生类添加不同的属性#》经验,为你挑选了1个好方法。

我有一个名为event的基类和2个名为sendEvent和receiveEvent的子类.你可以看到下面的代码:

namespace App
{
    public class Event
    {
        public Type type { get; set; }
        public Details details { get; set; }
    }

    public class Details
    {
        public string timestamp { get; set; }
        public string reference { get; set; }
        public string id { get; set; }
        public string correlator { get; set; }
        public string device1 { get; set; }
        public string device2 { get; set; }
        public string device3 { get; set; }
    }

    public class Details
    {
        public string timestamp { get; set; }
        public string reference { get; set; }
        public string primaryid { get; set; }
        public string primary_correlator { get; set; }
        public string secondaryid { get; set; }
        public string secondary_correlator { get; set; }
        public string device4 { get; set; }
        public string device5 { get; set; }
    }

    class ReceiveEvent : Event
    {
       public ReceiveEvent()
        {
            this.type = Type.Recieve;
        }


    }
    class SendEvent : Event
    {
        public SendEvent()
        {
            this.type = Type.Send;
        }
    }


    public enum Type
    {
       Send,
        Receive
    }
}

我希望sendEvent使用第一个细节,而receiveEvent使用第二个细节类.我无法弄清楚如何才能实现这一目标.你有什么想法吗?



1> D Stanley..:

一种选择是将公共字段分成基类并创建子类:

public class Details
{
    public string timestamp { get; set; }
    public string reference { get; set; }
}

public class SendDetails : Details
{
    public string id { get; set; }
    public string correlator { get; set; }
    public string device1 { get; set; }
    public string device2 { get; set; }
    public string device3 { get; set; }
}

public class ReceiveDetails : Details
{
    public string primaryid { get; set; }
    public string primary_correlator { get; set; }
    public string secondaryid { get; set; }
    public string secondary_correlator { get; set; }
    public string device4 { get; set; }
    public string device5 { get; set; }
}

然后让你的Event类通用:

public class Event where TDetail : Details
{
    public Type type { get; set; }
    public TDetail details { get; set; }
}

public class ReceiveEvent : Event
{
   public ReceiveEvent()
    {
        this.type = Type.Recieve;
    }
}

public class SendEvent : Event
{
    public SendEvent()
    {
        this.type = Type.Send;
    }
}

这样,您可以details从基本事件类或子类以强类型方式访问.

推荐阅读
低调pasta_730
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有