如何强制实现 C# 对象的所有字段?

How to force to implement all fields a C# object?

我在 class 库(项目 "A" 上有这个对象,我想在我的多个项目("B" 和 "C")中使用它:

public class Notification : INotification
{
    public string Id { get; set; }

    public int Type { get; set; }

    public IList<Message> Messages { get; set; }
}
public class Message: IMessage
{
    public string Key { get; set; }

    public string Value { get; set; }

    public string Culture { get; set; }
}
public interface INotification
{
    string Id { get; set; }

    int Type { get; set; }

    IList<Message> Messages { get; set; }
}

现在,如果我想在我的项目中创建这个对象"B",我需要进行以下操作:

static void Main()
{
    Notification notification = new Notification()
    {
        Id = "someId",
        Type = 1,
        Messages = new List<Message>()
        {
            new Message()
            {
                Culture = "en-US",
                Key = "Some key",
                Value = "Some value"
            }
        }
    };

    Console.WriteLine(notification.Id);
}

问题是,因为如果我不初始化所有字段都需要 Required,例如 "Type",则不会显示任何错误。我想要的是我的项目 "B" 像我想要的那样实现 "Notification" 对象,具有所有必填字段,因此没有 "Type" 就无法创建我的消息。 我怎样才能做到这一点?我需要创建抽象吗?

在 c# 中,要求字段初始化的方法是将它们作为构造函数参数提供。

public class Notification : INotification
{
    public Notification(string id, int type, IList<Message> messages)
    {
        this.Id = id;
        this.Type = type;
        this.Messages = messages;
    }

    public string Id { get; set; }

    public int Type { get; set; }

    public IList<Message> Messages { get; set; }
}

没有默认构造函数,现在无法在不指定类型的情况下构造通知。这是在编译时强制执行的,而不是 运行 时。

如果您想要空值检查,您必须自己将它们添加为构造函数逻辑的一部分。您还可以为 int 或其他验证添加范围检查。

注意:Type 是一个糟糕的变量名称。