扩展时的 C# OOP 特定参数 class
C# OOP specific params while extending class
我有一个 class ClassA,它有一个 class AttA 类型的受保护 属性,一个从 ClassA 扩展的 class ClassB 和一个 class从 AttA 扩展的 AttB。
在 class ClassA 中,我想使用 属性 AttA,但在 class ClassB 中,我想使用更具体的 属性 AttB。
有办法吗?
class ClassA
{
protected AttA att;
public void MyMethod()
{
// using att as AttA
}
}
class ClassB : ClassA
{
public override void MyMethod()
{
// Want to use att as AttB (if possible without downcasting)
}
}
谢谢。
一个简单的方法是使用new
关键字:
class ClassA
{
protected AttA att;
public virtual void MyMethod()
{
}
}
class ClassB : ClassA
{
new protected AttB att;
public override void MyMethod()
{
}
}
class AttA
{
}
class AttB : AttA
{
}
但这可能会导致使用多态性出现问题,因为写入:
var b = new ClassB();
//b.att is type of AttB here
var a = (ClassA)b;
//a.att is type of AttA here and it is not the same variable
事实上,根据您操作的类型,有两个字段 att
,因此在 classes 实现中要小心,尤其是从子 class 调用基本成员时。
由于该字段受保护,因此问题有限。
相反,这可能正是我们所需要的。
https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/new-modifier
我试图找到一个泛型解决方案,但由于 C# 不支持真正的泛型多态性,而且我们不能将泛型类型参数约束在一种类型上用于一种 class 类型,据我所知,这是不可能的 - 或者它需要使用反射编写一些代码,除非有必要,否则可以在这里过度设计(因此可以在 classes 层次结构之间使用相同的变量来公开所需的多态类型) .
我有一个 class ClassA,它有一个 class AttA 类型的受保护 属性,一个从 ClassA 扩展的 class ClassB 和一个 class从 AttA 扩展的 AttB。
在 class ClassA 中,我想使用 属性 AttA,但在 class ClassB 中,我想使用更具体的 属性 AttB。
有办法吗?
class ClassA
{
protected AttA att;
public void MyMethod()
{
// using att as AttA
}
}
class ClassB : ClassA
{
public override void MyMethod()
{
// Want to use att as AttB (if possible without downcasting)
}
}
谢谢。
一个简单的方法是使用new
关键字:
class ClassA
{
protected AttA att;
public virtual void MyMethod()
{
}
}
class ClassB : ClassA
{
new protected AttB att;
public override void MyMethod()
{
}
}
class AttA
{
}
class AttB : AttA
{
}
但这可能会导致使用多态性出现问题,因为写入:
var b = new ClassB();
//b.att is type of AttB here
var a = (ClassA)b;
//a.att is type of AttA here and it is not the same variable
事实上,根据您操作的类型,有两个字段 att
,因此在 classes 实现中要小心,尤其是从子 class 调用基本成员时。
由于该字段受保护,因此问题有限。
相反,这可能正是我们所需要的。
https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/new-modifier
我试图找到一个泛型解决方案,但由于 C# 不支持真正的泛型多态性,而且我们不能将泛型类型参数约束在一种类型上用于一种 class 类型,据我所知,这是不可能的 - 或者它需要使用反射编写一些代码,除非有必要,否则可以在这里过度设计(因此可以在 classes 层次结构之间使用相同的变量来公开所需的多态类型) .