使用基类创建对象时,无法访问派生类属性

时间:2014-02-14 12:17:20

标签: 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 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'
     }
}

2 个答案:

答案 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();