问题标题似乎有点混乱,但我会在这里试着澄清我的问题.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public abstract class Employee
{
private string name;
private int empid;
BenefitPackage _BenefitPackage = new BenefitPackage();
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public int EmpId
{
get { return this.empid; }
set
{
if (value == 1)
return;
this.empid = value; }
}
public Employee(string Name, int EmpId)
{
this.Name = Name;
this.EmpId = EmpId;
}
public Employee() …Run Code Online (Sandbox Code Playgroud) 浏览一些遗留代码时,我很惊讶地遇到了一个抽象覆盖的成员,它本身就是抽象的.基本上,这样的事情:
public abstract class A
{
public abstract void DoStuff();
}
public abstract class B : A
{
public override abstract void DoStuff(); // <--- Why is this supported?
}
public abstract class C : B
{
public override void DoStuff() => Console.WriteLine("!");
}
Run Code Online (Sandbox Code Playgroud)
编译器是否始终可以使用虚拟或抽象成员之间的区别?为什么C#支持这个?
(这个问题与C#中'抽象覆盖'的用法有什么不重复? 因为DoStuff类中的-method A不是虚拟的,而是抽象的.)
public abstract class A
{
public abstract void Process();
}
public abstract class B : A
{
public abstract override void Process();
}
public class C : B
{
public override void Process()
{
Console.WriteLine("abc");
}
}
Run Code Online (Sandbox Code Playgroud)
此代码抛出编译错误:'B'不实现继承的抽象成员'A.Process()'.
有没有办法做到这一点?
我试图运行在C#中下面的示例程序,我得到的输出"你要一部电脑",而不是"你得到一台电脑和一盘和一个显示器和键盘".
为什么这只发生在C#中,而不是在Java中.我java相同的代码我得到了适当的输出.
如果我调试我发现创建的对象层次结构是正确的但是调用computer.getComputer()总是去超级类而不是驱动类,这就是问题所在.
请帮我解决这个问题.
namespace DecoratorTest1
{
public class Computer
{
public Computer()
{
}
public String getComputer()
{
return "computer";
}
}
public abstract class ComponentDecorator : Computer
{
public abstract String getComputer();
}
public class Disk : ComponentDecorator
{
Computer computer;
public Disk(Computer c)
{
computer = c;
}
public override String getComputer()
{
return computer.getComputer() + " and a disk";
}
}
public class Monitor : ComponentDecorator
{
Computer computer;
public Monitor(Computer c)
{
computer = c; …Run Code Online (Sandbox Code Playgroud) 让我们看看以下类结构:
abstract class Base {
public abstract void DoSth();
}
class Derived1 : Base {
public override void DoSth() {
}
}
Run Code Online (Sandbox Code Playgroud)
这些是某些层次结构的基类.现在,让我们假设,我们要提供从另一个类派生Derived1(让我们叫它Derived2),它不应该使用的默认实现DoSth提供Default1.例如,Derived1涵盖了98%的案例,但在剩余的2%中,此解决方案是不可接受或危险的.
最好的解决方案是通知派生出来的人Derived2,他应该在编译期间实现DoSth.怎么做?