我有一个名为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使用第二个细节类.我无法弄清楚如何才能实现这一目标.你有什么想法吗?
一种选择是将公共字段分成基类并创建子类:
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 Eventwhere 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
从基本事件类或子类以强类型方式访问.