0 .net c# polymorphism inheritance
我有一个继承自另一个的类,我想使用其中一个基类函数...但我遇到一个问题,调用基函数不会从继承的类返回成员变量,因为我希望.
为了说明我的问题,我创建了一个简化的例子.我希望这个例子输出"5",但它没有:)解决方案似乎是我需要将myclass1中的getInt()函数复制到myclass2中...然后它会起作用,但这似乎打败了从myclass1继承的要点(我想避免在每个类中复制该函数).
class Program
{
static void Main(string[] args)
{
myclass2 myclass = new myclass2();
// Expected to output 5, but it actually outputs 0
Console.WriteLine( myclass.getInt() );
}
}
struct s1
{
public string str;
public int num;
}
struct s2
{
public int num;
public int num2;
}
class myclass1
{
internal s1 mystruct;
internal int getInt()
{
return mystruct.num;
}
}
class myclass2 : myclass1
{
internal new s2 mystruct;
internal myclass2()
{
mystruct.num = 5;
}
}
Run Code Online (Sandbox Code Playgroud)
你是隐藏myclass1.mystruct用myclass2.mystruct.它们是两个完全不同的对象.
您可以通过virtual在基类和override子类中创建对象来覆盖该对象,但该对象必须保持其类型.您无法更改实例的类型,因为这不是类型安全的.(FIXME)如果你想改变类型mystruct,为什么?
我想,如果您只是想从中访问myclass1.mystruct,myclass2可以使用base.mystruct.