C#的简单继承问题 [英] Simple inheritance problem with C#
本文介绍了C#的简单继承问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个班,动物和狗。狗继承自动物类。为什么我无法使用dog.b访问字段b?如果狗继承自Animal,那么它应该知道b吗?
I have 2 classes, Animal and dog. dog inherits from Animal class. How come i am not able to access the field b with dog.b ? If dog inherits from Animal , then should it know about b ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace inheritance1
{
class Program
{
static void Main(string[] args)
{
Animal a = new Animal();
a.b = 5;
Console.WriteLine(a.b);
dog d = new dog();
dog.b = 4;
Console.WriteLine(dog.b);
Console.ReadKey();
}
}
class Animal
{
public int b = 3;
}
class dog : Animal
{
}
}
我尝试过:
dog.b = 4;
What I have tried:
dog.b = 4;
推荐答案
您可以访问b
使用dog实例的字段,但这里的问题是你直接使用类名而不是实例变量,你需要使用d
来调用它喜欢:
You can access theb
field using the dog instance, but the problem here is you are using class name directly instead of instance variable, you need to call it usingd
like :
dog d = new dog();
d.b = 4; // note this, use instance variable not class name
这篇关于C#的简单继承问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文