use*_*454 -2 c# inheritance class
我有一个名为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
}
}
Run Code Online (Sandbox Code Playgroud)
我希望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; }
}
Run Code Online (Sandbox Code Playgroud)
然后让你的Event类通用:
public class Event<TDetail> where TDetail : Details
{
public Type type { get; set; }
public TDetail details { get; set; }
}
public class ReceiveEvent : Event<ReceiveDetails>
{
public ReceiveEvent()
{
this.type = Type.Recieve;
}
}
public class SendEvent : Event<SendDetails>
{
public SendEvent()
{
this.type = Type.Send;
}
}
Run Code Online (Sandbox Code Playgroud)
这样,您可以details从基本事件类或子类以强类型方式访问.