【发布时间】: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