1

这是我所拥有的:

public interface IEvent {
  int Id
  string Title

}

public class MeetingEvent : IEvent {
  int Id
  string Title

  //Meeting Properties
  string Room;
  User Organizer; 
}

public class BirthdayEvent : IEvent {
  int Id
  string Title

  //Bday Properties
  int Candles;
  bool Surprise;
}

我正在使用 ASP.NET MVC 中的自定义模型绑定器,因为我的主编辑表单继承自 IEvent,而我执行 RenderPartial 以添加其他特定于类型的字段

当我到达模型绑定器时,我可以看到该类型的所有键/值,这很好。现在,我想这样做:

IEvent _event;

switch (eventType) {  // EventType is an enum
  case EventType.Birthday:
    _event = new BirthdayEvent();

    _event.Candles= GetValue<int>(bindingContext, "Candles");
    _event.Surprise= GetValue<bool>(bindingContext, "Surprise");
    break;

  case EventType.Meeting:
    _event = new MeetingEvent();

    // Meeting-specific fields are set here...
    break;

  default:
    throw new InvalidOperationException("Invalid Event Type");
}

本质上,我想要一个 IEvent 变量,并且我想创建一个实现 IEvent 并设置特定类型字段的特定事件类型。Visual Studio 告诉我的是它无法访问 BirthdayEvent 字段。

虽然,我明白这一点,但我似乎无法弄清楚我需要做什么。

4

2 回答 2

3

当您第一次创建 and 的实例时BirthdayEventMeetingEvent将它们放入该类型的变量中。这样您就可以分配这些成员。然后将它们分配给您的_event变量。像这样:

switch (eventType) {  // EventType is an enum
  case EventType.Birthday:
  {
    var be = new BirthdayEvent();

    be.Candles= GetValue<int>(bindingContext, "Candles");
    be.Surprise= GetValue<bool>(bindingContext, "Surprise");
    _event = be;
    break;
  }
  case EventType.Meeting:
  {
    var me = new MeetingEvent();

    // Meeting-specific fields are set here...
    _event = me;
    break;
  {
  default:
    throw new InvalidOperationException("Invalid Event Type");
}
于 2010-02-22T15:21:09.990 回答
2

这些方面的东西:

IEvent _event;

switch (eventType) {  // EventType is an enum
  case EventType.Birthday:
    var birthdayEvent = new BirthdayEvent();

    birthdayEvent.Candles= GetValue<int>(bindingContext, "Candles");
    birthdayEvent.Surprise= GetValue<bool>(bindingContext, "Surprise");
    _event = birthdayEvent;
    break;
  /* etc */

  default:
    throw new InvalidOperationException("Invalid Event Type");
}
于 2010-02-22T15:22:53.913 回答