2

I have the following

public enum MessageType
{
    Warning,
    Info,
    Error
}

public class CalculationMessage
{
    public string Message { get; set; }

    public MessageType Type { get; set; }

}

public class ValidationMessage
{
    public string Message { get; set; }

    public MessageType Type { get; set; }

    public string ErrorValue { get; set; }
}

I am trying to create a base class from which both of these classes are derived, however I have a problem with the enum as a ValidationMessage can be Error / Warning / Info but a CalculationMessage can only be Warning or Info.

How is this best achieved?

Thanks in advance.

4

1 回答 1

3

您可以在 setter 中添加参数验证:

set
{
  if(value == MessageType.Warning || value == MessageType.Info)
  {
    this.messageType = value;
  }
  else
  {
    throw new ArgumentOutOfRangeException();
  }
}

然而,这违反了 Liskov 替换原则。因此要小心并考虑是否有办法解决(例如根本不公开设置器,而是在MessageType内部确定)。

于 2012-09-19T15:21:34.927 回答