我无法从基类对象名访问派生类属性。
我的动机是我需要消除在类中重复的属性,并且需要使用基类名创建对象。
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'
}
}
答案 0 :(得分:0)
req
的类型为Request
,即使它已使用Permission
进行实例化。
属性FromTime
仅存在于Permission
而不存在于基类中。
你应该这样做
Permission p = new Permission();
p.FromTime = DateTime.Now; //now works`
如果您需要使用Permission
Permission
((Permission)req).FromTime = ...
答案 1 :(得分:0)
您将变量定义为基类,因此她只能访问peropriedade相同的
Permission req = new Permission();