修改接口实现中特定于类型的属性
这是我所拥有的:
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字段。
虽然我明白这一点,但我似乎不知道我需要做什么。
Here is what I have:
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;
}
I am working on a custom model binder in ASP.NET MVC as my main edit form inherits from IEvent while I perform a RenderPartial to add the other type-specific fields
When I get to the model binder, I can see all the keys/values for the type, which is good. Now, I want to do this:
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");
}
In essence, I want an IEvent variable and I want to create a specific event type that implements IEvent and set the type-specific fields. What Visual Studio tells me is that it can not access the BirthdayEvent fields.
While, I understand this, I can't seem to figure out what I need to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您首次创建
BirthdayEvent
和MeetingEvent
实例时,将它们放入该类型的变量中。这样您就可以分配这些成员。然后将它们分配给您的_event
变量。像这样:When you first create your instances of
BirthdayEvent
andMeetingEvent
, put them in variables of that type. That way you can assign those members. Then assign them to your_event
variable. Like this:沿着这些思路:
Something along these lines: