Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用基类创建对象时无法访问dervied类属性_C#_Object_Inheritance_Polymorphism_Polymorphic Associations - Fatal编程技术网

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;}
这将适用于所有派生类型的
请求