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

Kir*_*512 0 c# inheritance abstract-class interface object

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

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

    public int Type { get; set; }

    public IList<Message> Messages { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
public class Message: IMessage
{
    public string Key { get; set; }

    public string Value { get; set; }

    public string Culture { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
public interface INotification
{
    string Id { get; set; }

    int Type { get; set; }

    IList<Message> Messages { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我想在我的项目“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);
}
Run Code Online (Sandbox Code Playgroud)

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

Joh*_* Wu 6

在 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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

注意:Type对于变量来说这是一个糟糕的名称。