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

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

问题描述

据我所知,在 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;
        }
    }
}

我通过在派生类中将属性创建为new"来解决这个问题,但这当然不是多态的.

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 语言中都是不可能的.在类型安全的语言中,您必须为返回值提供协方差,并为参数提供逆变.拿这个代码:

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

对于 Get 方法,协方差意味着 T 必须是 S 或从 S 派生的类型.否则,如果您对 D 类型的对象的引用存储在类型为 B 的变量中,则当您调用 B.Get() 时,您不会得到一个可表示为 S 的对象——打破了类型系统.

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.

对于 Set 方法,逆变意味着 T 必须是 SS 派生的类型从.否则,如果您在调用 B.Set(X) 时,对存储在类型为 B 的变量中的 D 类型的对象的引用,其中 XS 类型但不是 T 类型,D::Set(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 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 的类型,但不能同时带有 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天全站免登陆