【问题标题】:How to force to implement all fields a C# object?如何强制实现 C# 对象的所有字段?
【发布时间】:2020-03-28 03:19:47
【问题描述】:

我在一个类库中有这个对象(我想在我的多个项目中使用的项目“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,如果我不初始化例如“类型”,则不会显示错误。我想要的是我的项目“B”像我想要的那样实现“通知”对象,包含所有必填字段,所以没有“类型”就无法创建我的消息。 我怎样才能做到这一点?我需要创建抽象吗?

【问题讨论】:

  • 这不是继承问题,您可以简单地将所有字段设为私有并在构造函数中执行逻辑以确保设置所有属性。
  • 这是 .NET 还是 .NET Core?
  • 您希望[Required] 属性能做什么?
  • 我认为你应该将你的接口转换为抽象类
  • @nAviD .net 核心

标签: c# object inheritance interface abstract-class


【解决方案1】:

在 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 是一个可怕的变量名称。

【讨论】:

  • 由于id 仍可能是null,您可能需要考虑添加this.id = id ?? throw new ArgumentNullException(nameof(id));Messages 如果为 null,则可以设置为空列表,但这取决于要求。
  • 所以有了这个,我需要实现我其他项目中的所有字段。是的,我会将Type 更改为NotificationType。感谢您的帮助!
猜你喜欢
  • 2011-02-02
  • 2014-11-10
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 2010-11-11
  • 1970-01-01
相关资源
最近更新 更多