【问题标题】:cannot access dervied class properties when object created using base class使用基类创建对象时无法访问派生类属性
【发布时间】:2014-03-13 19:19:13
【问题描述】:

我无法从基类对象名称访问派生类属性。

我的动机是我需要消除类中重复的属性,并且需要使用基类名称创建对象。

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'
     }
}

【问题讨论】:

    标签: c# object inheritance polymorphism polymorphic-associations


    【解决方案1】:

    req 的类型是 Request,即使它是用 Permission 实例化的。

    属性FromTime 仅存在于Permission 中,而不存在于基类中。

    你应该这样做

    Permission p = new Permission();
    p.FromTime = DateTime.Now; //now works`
    

    如果您需要使用来自Permission 的属性,您可以将req 转换为Permission

    ((Permission)req).FromTime = ...

    【讨论】:

    • Ric -> 在哪种情况下我们需要创建像“Request req = new Permission();”这样的对象
    • 如果您只需要从基访问属性/方法而不知道或关心实际派生类型(例如 Permission 或 Leave)或创建只接受 Request 类型参数的方法,例如作为void DoStuff(Request r) { r.IsApproved = false; },它适用于Request的所有派生类型
    【解决方案2】:

    你将你的变量定义为基类,所以她只能访问相同的 peropriedades

    Permission req = new Permission();
    

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      • 2022-07-20
      • 2015-08-10
      • 1970-01-01
      • 2013-08-16
      • 1970-01-01
      相关资源
      最近更新 更多