2

我有具有抽象属性的基类。我希望所有继承类都覆盖抽象属性。例子:

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类型的 Some 属性。我Someone在我的TestClass. 现在我想使用Employeetype 而不是Person. 我的Employee类继承自Person. 我无法让它工作。我应该怎么做才能避免这个问题?

帮助表示赞赏!

4

4 回答 4

1

问题是您可以将 Employee 分配给 Person 实例,但不能也将 Person 分配给 Employee 实例。因此,您的二传手会中断。您要么需要摆脱 setter,要么使用私有支持实例和一些强制转换(我不推荐),如下所示:

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;
        }
}
于 2013-05-16T21:20:43.123 回答
1

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; }
}
于 2013-05-16T21:39:54.893 回答
0

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

See Eric Lippert's answer here.

于 2013-05-16T21:23:57.797 回答
0

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.

于 2013-05-16T21:46:42.590 回答