我可以派生类型覆盖? [英] Can I Override with derived types?

查看:106
本文介绍了我可以派生类型覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我知道这是不可能做到在下面的C#2.0

As far as i know it is not possible to do the following in C# 2.0

public class Father
{
    public virtual Father SomePropertyName
    {
        get
        {
            return this;
        }
    }
}

public class Child : Father
{
    public override Child SomePropertyName
    {
        get
        {
            return this;
        }
    }
}

我通过如新派生类创建属性解决该问题,但当然不是多态

I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic.

public new Child SomePropertyName

是否有任何2.0的解决方案?
怎么样在3.5,解决这个问题的功能?

Is there any solution in 2.0? What about any features in 3.5 that address this matter?

推荐答案

编辑:我刚刚醒来的时候,我写了原来的答复,我想我做到了比清楚一点点少了,用错了字几次。下面是修改后的版本,说同样的事情,但(我希望)解释好,并使用正确的术语。

这是不可能的,因为类型安全的担忧任何.NET语言。在类型安全的语言,你必须为返回值提供协方差和逆变的参数。借此code:

This is not possible in any .NET language because of type-safety concerns. In type-safe languages, you must provide covariance for return values, and contravariance for parameters. Take this code:

class B {
    S Get();
    Set(S);
}
class D : B {
    T Get();
    Set(T);
}

对于获取方法,协方差意味着 T 必须是取值取值。否则,如果你不得不类型的对象的引用 D 存储在类型 B ,当你叫一个变量 B.Get()你不会得到一个对象重新presentable为取值回 - 打破类型系统。

For the Get methods, covariance means that T must either be S or a type derived from S. Otherwise, if you had a reference to an object of type D stored in a variable typed B, when you called B.Get() you wouldn't get an object representable as an S back -- breaking the type system.

对于设置方法,逆变意味着 T 必须是取值或类型取值从派生。否则,如果你有一个referencea引用类型的对象 D 存储在类型 B ,一个变量,当你叫 B.Set(X),其中 X 是类型取值而不是类型 T D ::套装(T)会得到一个类型它确实的对象没想到。

For the Set methods, contravariance means that T must either be S or a type that S derives from. Otherwise, if you had a referencea reference to an object of type D stored in a variable typed B, when you called B.Set(X), where X was of type S but not of type T, D::Set(T) would get an object of a type it did not expect.

在C#中,有一个明智的决定,禁止超载的属性时改变的类型,即使他们只掌握的getter / setter对中的一个,因为它本来有非常不一致的行为(的你的意思是,我可以改变一个与吸气的类型,却没有一个同时具有getter和setter为什么不的 - ?!?。匿名备用的宇宙新手)

In C#, there was a conscious decision to disallow changing the type when overloading properties, even when they have only one of the getter/setter pair, because it would otherwise have very inconsistent behavior ("You mean, I can change the type on the one with a getter, but not one with both a getter and setter? Why not?!?" -- Anonymous Alternate Universe Newbie).

这篇关于我可以派生类型覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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