Inheriting abstract classes with abstract properties

亡梦爱人 提交于 2019-12-14 02:00:04

问题


I have base class with abstract properties. I want all inheriting classes to override abstract properties. Example:

public class Person
{
    public string Name{get;set;}
    public string LastName{get;set;}
}

public class Employee : Person
{
    public string WorkPhone{get;set;}
}

public abstract class MyBase
{
    public abstract Person Someone {get;set;}
}

public class TestClass : MyBase
{
    public override Employee Someone{get;set;} //this is not working
}

Base class has Someone property with Person type. I am overriding Someone property on my TestClass. Now I want to use Employee type instead of Person. My Employee class inherits from Person. I couldn't make it work. What should I do to avoid this problem?

Help appreciated!


回答1:


The problem is that you may be able to assign an Employee to a Person instance, but you can't also assign a Person to Employee instance. Therefore, your setter would break. You either need to get rid of the setter, or use a private backing instance and some casting (which I wouldn't recommend) which would look like:

public class TestClass : MyBase
{
    private Employee _employee;

    public Person Someone
    {
        get
        {
            return _employee;
        }
        set
        {
            if(!(value is Employee)) throw new ArgumentException();
            _employee = value as Employee;
        }
}



回答2:


You could use Generics if you want derived classes to use ethier Employee or Person

Something like:

public class Person
{
    public string Name { get; set; }
    public string LastName { get; set; }
}

public class Employee : Person
{
    public string WorkPhone { get; set; }
}

public abstract class MyBase<T> where T : Person
{
    public abstract T Someone { get; set; }
}

public class TestClass : MyBase<Employee>
{
    public override Employee Someone { get; set; } 
}

public class TestClass2 : MyBase<Person>
{
    public override Person Someone { get; set; }
}



回答3:


This is a form of return type covariance, which is not allowed in C# unfortunately.

See Eric Lippert's answer here.




回答4:


In short: Each Employee object is a Person object. But not every Person object is an Employee object.

That's why compiler complains because you want it to treat an Employee object as a Person object in some place that a Person is explicitly required - which can be any object derived from Person including Employee; not specifically Employee.

Note: @sa_ddam213 provided a solution in her/his answer if you really need to do this explicitly.



来源:https://stackoverflow.com/questions/16597653/inheriting-abstract-classes-with-abstract-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!