c# - 如何约束分配给 Type 类型变量的类型?

标签 c# types

[注意:编辑以包含创建 FollowUpEvent 集合的要求]

我正在编写一个日历系统。我有一个基本类型 CalendarEvent,以及一个适度复杂的后代类型层次结构(AppointmentEventReminderEventAppointmentInOfficeEvent , 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/

相关文章:

c# - Fluentvalidation 无法使用本地化名称

c# - 合并mysql中两个数据集的结果

c# - 提交表单时获取查询字符串值...MVC3

c# - 结构 - 现实生活中的例子?

c# - 任何列中 DataGridView 标题中的复选框

python - python 中的简单类型与复杂类型?

转换为无符号字符

c# - 使用动态类型调用泛型扩展方法

types - f# 中用户定义类型的混淆

c# - 运算符 '??' 不能应用于类型 'string' 和 'System.DBNull' 的操作数