C# 使用基类创建对象时无法访问dervied类属性
我无法从基类对象名访问派生类属性 我的动机是我需要消除类中重复的属性,并且需要使用基类名称创建对象C# 使用基类创建对象时无法访问dervied类属性,c#,object,inheritance,polymorphism,polymorphic-associations,C#,Object,Inheritance,Polymorphism,Polymorphic Associations,我无法从基类对象名访问派生类属性 我的动机是我需要消除类中重复的属性,并且需要使用基类名称创建对象 public abstract class Request { public int RequestId { get; set; } public string Reason { get; set; } public bool IsApproved { get; set; } public bool IsRejected { get; set; }
public abstract class Request
{
public int RequestId { get; set; }
public string Reason { get; set; }
public bool IsApproved { get; set; }
public bool IsRejected { get; set; }
public Employee Employee { get; set; }
}
public class Permission : Request
{
public DateTime FromTime { get; set; }
public DateTime ToTime { get; set; }
public PermissionType PermissionType { get; set; }
}
public class Leave: Request
{
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public LeaveType LeaveType { get; set; }
}
class Program
{
static void Main(string[] args)
{
Request req = new Permission();
req.Reason = 1;
req.Reason = "232";
req.FromTime = DateTime.Now; // Here i'm getting error as 'Request does not contain definition'
req.ToTime = DateTime.Now.AddHours(1); // Here i'm getting error as 'Request does not contain definition'
}
}
req
的类型是Request
,即使它是用权限实例化的
属性FromTime
仅存在于Permission
中,而不存在于基类中
你应该这样做
Permission p = new Permission();
p.FromTime = DateTime.Now; //now works`
如果需要使用Permission
((Permission)req).FromTime=…
您正在将变量定义为基类,因此她只能访问相同的peropriedades
Permission req = new Permission();
Ric->在哪种情况下,我们需要创建“Request req=new Permission();”这样的对象,如果您只需要从基访问属性/方法,而不知道或关心实际的派生类型,例如Permission或Leave,或者创建一个只接受Request
类型的参数的方法,例如void DoStuff(Request r){r.IsApproved=false;}
这将适用于所有派生类型的请求