C# 使用派生类重写基类的属性
在C代码中,如果C# 使用派生类重写基类的属性,c#,inheritance,properties,polymorphism,C#,Inheritance,Properties,Polymorphism,在C代码中,如果钢筋类源自钢筋类,且钢筋形状类继承了钢筋形状类。是否可以使用RebarShape类重写基类中的属性reinforcmentshape public class ReinforcementShape { } public class RebarShape : ReinforcementShape { } public class Reinforcement { public ReinforcementShape S
钢筋
类源自钢筋
类,且钢筋形状
类继承了钢筋形状
类。是否可以使用RebarShape
类重写基类中的属性reinforcmentshape
public class ReinforcementShape
{
}
public class RebarShape : ReinforcementShape
{
}
public class Reinforcement
{
public ReinforcementShape Shape { get; set; }
}
public class Rebar : Reinforement
{
// I want to override the Shape property
// but with its derived class which is RebarShape
// override the base property somehow!
public RebarShape Shape { get; set; }
}
更新:
public virtual ReinforcementShape Shape { get; set; }
public new RebarShape Shape { get; set; }
当前的实现有什么问题
在底部:
public virtual ReinforcementShape Shape { get; set; }
public new RebarShape Shape { get; set; }
在派生中:
public virtual ReinforcementShape Shape { get; set; }
public new RebarShape Shape { get; set; }
您可以使用
new
关键字来执行此操作。因此,钢筋类的定义如下所示
public class Rebar : Reinforement
{
public new RebarShape Shape
{
get { return (RebarShape)base.Shape; }
set { base.Shape = value; }
}
}
可以使用泛型执行此操作,无需重写基类成员:
public class Reinforcement<T> where T: ReinforcementShape
{
public <T> Shape { get; set; }
}
public class Rebar : Reinforement<RebarShape>
{
}
尝试将增强形状
的实例分配给该属性将导致编译时错误,此时只有rebar形状
有效
编辑:根据您的编辑。您只能通过覆盖成员的实现而不是返回值来覆盖成员。因此,在您的情况下,使用virtual
不会起任何作用。然而,正如R.Rusev已经提到的,您只需要在派生成员上使用new
-关键字,它实际上将提供一个与基类中的成员同名的全新成员。但实际上,它是一个完全不同的成员,与前一个成员毫无共同之处。但是,当您编写以下内容时
Reinforcement r = new Rebar();
// assign value to Shape
var shape = r.Shape;
使用的是原始实现,而不是新实现。因此,形状
将是加固形状
类型,而不是钢筋形状
。唯一的解决方法是首先将r
声明为Rebar
:
Rebar r = new Rebar();
// assign value to Shape
var shape = r.Shape;
但这对应用程序的任何用户来说都是相当混乱的,也许对您自己也是如此。我一般不建议使用这个关键词。最好使用第一种方法。new-关键字不会覆盖,而是隐藏基类的实现。无论如何,即使使用关键字,当您使用派生类的实例作为基类的变量时,也会使用原始成员,而不是新成员。谢谢。你能给我看一下基类中的实现吗。我希望也能在基类中设置。@Vahid基类保持不变。@HimBromBeere您是对的。我只是觉得这就是瓦希德想做的。因此,他不必每次使用钢筋时都铸造钢筋形状。您不能重写属性并更改其返回类型。不幸的是,我不能使用泛型。因为我需要对这些类的几个属性执行此操作。@Vahid:那么您应该将其他属性添加到您的问题中。一般来说,泛型是更好的方法(与
new
关键字答案相比)