[注意:编辑以包含创建 FollowUpEvent 集合的要求]
我正在编写一个日历系统。我有一个基本类型 CalendarEvent
,以及一个适度复杂的后代类型层次结构(AppointmentEvent
、ReminderEvent
、AppointmentInOfficeEvent
, ETC)。我还想创建一个模式结构,为每个事件指定应创建的后续事件列表:
public class FollowUpEvent
{
public Type EventType { get; set; };
public int OffsetDays { get; set; };
public bool IsRequired { get; set; };
}
static List<FollowUpEvent> EventsToAdd = new FollowUpEvent()
{
new FollowUpEvent() { EventType = typeof(ReminderEvent), OffsetDays = 7, IsRequired = true },
new FollowUpEvent() { EventType = typeof(ReminderEvent), OffsetDays = 14, IsRequired = false }
}
问题是 EventType
属性将接受任何 对象类型,我想装饰性地将它限制为 CalendarEvent
及其后代。我知道我可以在 setter 中执行此操作,但理想情况下我想在属性声明中表达它。
这可能吗?
(我来自 Delphi 背景,我认为我正在寻找的是等同于 MyType = class of CalendarEvent
声明。)
最佳答案
我认为以下内容没有意义,但如果您不想存储实际的 CalendarEvent
对象,它会起作用:
public class FollowUpEvent<T> where T: CalendarEvent
{
public Type EventType { get
{
return this.GetType().GetGenericArguments()[0]
// OR
// return typeof(T)
}
}
public int OffsetDays { get; set; };
public bool IsRequired { get; set; };
}
关于c# - 如何约束分配给 Type 类型变量的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20614885/