我想在C#中使用Java样式多态.可能吗?
这是一个不编译的例子
using System;
namespace HelloWorld
{
public class Program
{
public static void Main (string[] args)
{
Triangle triangle = new Triangle(2);
Square square = new Square(3);
printID(square);
}
public void printID(Shape s){
Console.WriteLine ("id is " + s.id);
}
}
public class Shape{
public int id;
}
public class Triangle: Shape{
float b;
float height;
float area(){
return b*height/2;
}
public Triangle(int k){
id=k;
}
}
public class Square: Shape{
float side;
float area(){
return side*side;
}
public Square(int k){
id=k;
}
}
}
Run Code Online (Sandbox Code Playgroud)
信息是
MyClass.cs(11,4):错误CS0120:访问非静态成员"HelloWorld.Program.printID(HelloWorld.Shape)"需要对象引用
谢谢!
错误与多态无关 - 您从静态方法调用非静态方法Main.你也应该制作printID静态.
public static void printID(Shape s){
Console.WriteLine("id is " + s.id);
}
Run Code Online (Sandbox Code Playgroud)
我还建议你:
public Shape(int id)在基类中创建构造函数,并通过派生类调用该构造函数: base(id)id而不是k.| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |