lsh*_*has 0 c# oop inheritance constructor class
在我C#度过了大半生的生活之后,我最近开始做一些编程PHP.
在PHP我能做到这一点:
class User
{
public __construct($UserId)
{
// Do stuff
}
}
class Employee extends User
{
public __construct($EmployeeId)
{
// Look up the UserId connected to $EmployeeId
$UserId = hypothetical_get_user_id_func($EmployeeId);
parent::__construct($UserId);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,C#我似乎没有这种可能性,因为$UserId在它进入第一个构造函数之前,我似乎必须知道它.
public class User
{
public User(int UserId)
{
// Do stuff
}
}
public class Employee : User
{
public Employee(int EmployeeId) : base(***) // I don't know this value yet?
{
// This is where I would find the User Id, and would like to pass
// it to the User class constructor.
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法实现我在C#中尝试做的事情?
基本上将值传递给主对象的构造函数,主对象在自己的主体中指出要传递给基类的值.
您可以在构造函数中调用静态方法.虽然非常不标准.
public class User
{
public User(int userId)
{
// Do stuff
}
}
public class Employee : User
{
public Employee(int employeeId) : base(GetUserId(employeeId))
{
}
public static int GetUserId(int employeeId)
{
return employeeId - 5;
}
}
Run Code Online (Sandbox Code Playgroud)