问题描述
据我知道这是不可能做到以下几点在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).
这篇关于C#我可以覆盖与派生类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!