2

来自 Java 或 Python,我习惯于制作这样的结构,通常它“正常工作”。最近发现了 C#,除了一些挫折之外,发现它使用起来非常愉快。

一种这样的挫败感是我必须通过多态构造(覆盖、虚拟等)来控制它。

这是一个这样的案例,我还没有找到如何“让工作”。

class Polymorphism
{
    public interface IPerson
    {
        String Name { get; set; }
    }

    public class Doctor : IPerson
    {
        public String Name { get; set; }
    }

    public class DoctorGroup
    {
        public IEnumerable<IPerson> Members
        {
            get
            {
                return DoctorMembers;
            }
        }

        public List<Doctor> DoctorMembers { get; set; }
        public DoctorGroup()
        {
            DoctorMembers = new List<Doctor>();
        }
    }
}

这里DoctorMembers是s,因此当被要求提供ofIPerson时,我应该能够只返回一份医生名单。 IEnumerableIPerson

public IEnumerable<IPerson> Members
{
    get
    {
        return DoctorMembers;
    }
}

然而......编译器抱怨......为什么?我错过了什么?这在语义上没有任何问题,到目前为止我使用过的大多数 OOP 语言都可以在没有句法 Pepto-Bismol 的情况下消化这一点。我是否缺少一个关键字以使其对编译器显而易见?

这里明显的捷径是将所有医生转换为 LINQ,IPerson但我不明白为什么这是必要的,甚至是可取的。

谁能点亮我的灯笼?

4

2 回答 2

10

此代码使用面向 .NET 4 的 C# 4 进行编译,但不会在 C# 3 中编译,因为 C# 3 没有泛型变量

基本上你想要一个从IEnumerable<Doctor>to的隐式转换IEnumerable<IPerson>。这是安全的,因为您只能从IEnumerable<T>...中“取出”值,这就是为什么在 .NET 4 中,它被声明为IEnumerable<out T>.

阅读更多关于通用方差的详细信息,并记住这仅在 C# 4 及更高版本中可用。

(If you have to use C# 3 or .NET 3.5, you can use the solution shown by CSharpie... but ideally, upgrade to a more recent version :)

于 2012-11-04T17:13:51.437 回答
3

试试这个:

public IEnumerable<IPerson> Members
{
    get
    {
        return DoctorMembers.Cast<IPerson>();
    }
}
于 2012-11-04T17:13:22.040 回答