继承具有抽象属性的抽象类 [英] Inheriting abstract classes with abstract properties

查看:175
本文介绍了继承具有抽象属性的抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有抽象属性的基类.我希望所有继承的类都覆盖抽象属性.示例:

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
}

基类具有Person类型的Someone属性.我要覆盖TestClass上的Someone属性.现在,我要使用Employee类型而不是Person.我的Employee类继承自Person.我无法使它工作.我应该怎么做才能避免这个问题?

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?

帮助表示赞赏!

推荐答案

问题是您可以将Employee分配给Person实例,但是也不能将Person分配给Employee实例.因此,您的安装员将中断.您要么需要摆脱设置器,要么使用私有的支持实例和一些强制转换(我不建议这样做),如下所示:

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

这篇关于继承具有抽象属性的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆