在运行时确定对象类型-C#
我有两个子类CalIntEvent和CalExtEvent,它们有两个属性custId和roomNumber。这些类继承自CalEvent 我有下面的代码,但无法访问派生类属性。如何访问这些在运行时确定对象类型-C#,c#,oop,C#,Oop,我有两个子类CalIntEvent和CalExtEvent,它们有两个属性custId和roomNumber。这些类继承自CalEvent 我有下面的代码,但无法访问派生类属性。如何访问这些 CalEvent newEvent; while (userAns != '1' && userAns != '2') { Console.WriteLine("\nPlease enter 1 for Internal Event or 2 for External Even
CalEvent newEvent;
while (userAns != '1' && userAns != '2')
{
Console.WriteLine("\nPlease enter 1 for Internal Event or 2 for External Event: ");
userAns = Console.ReadKey().KeyChar;
}
if (userAns == '1')
{
newEvent = new CalIntEvent();
}
else
{
newEvent = new CalExtEvent();
newEvent.custId = 2;// issue is here<<<<<<
}
newEvent.location = GetUserInput(Field.Location, "Please enter a location");
newEvent.title = GetUserInput(Field.Title, "Please enter a title");
newEvent.description = GetUserInput(Field.Description, "Please enter a description");
CalEvent新事件;
while(userAns!=“1”&&userAns!=“2”)
{
Console.WriteLine(“\n请输入1表示内部事件,输入2表示外部事件:”);
userAns=Console.ReadKey().KeyChar;
}
如果(userAns==“1”)
{
newEvent=new CalIntEvent();
}
其他的
{
newEvent=new CalExtEvent();
newEvent.custId=2;//问题就在这里因为custId
是在CalExtEvent
上定义的,所以您不能从类型为CalEvent
的变量访问它
您可以在构造CalExtEvent
时初始化该属性。下面是一个示例:
newEvent = new CalExtEvent() { custId = 2};
由于custId
是在CalExtEvent
上定义的,因此不能从CalEvent
类型的变量访问它
您可以在构造CalExtEvent
时初始化该属性。下面是一个示例:
newEvent = new CalExtEvent() { custId = 2};
为什么不通过CalExtEvent
的构造函数传递custId
?或者在创建如下对象时初始化它:newEvent=newcalextevent(){custId=2}
为什么不通过CalExtEvent
的构造函数传递custId
?或者在创建如下对象时初始化它:newEvent=newcalextevent(){custId=2};