在C#中使用基类和子类的基类实例之间的用途和区别是什么? [英] What is the use and difference between instance of a base class using base class and child class in C#?

查看:280
本文介绍了在C#中使用基类和子类的基类实例之间的用途和区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 BaseClass obj1 = new BaseClass(); 
BaseClass obj2 = new ChildClass();



是什么让obj2特别优于obj1?

如果有任何场景可以使obj2特别请引用相同的内容。



我尝试了什么:



我试过初始化对象两种方式和使用方法,它的参数看起来都只有我。

解决方案

一个子类继承它的基类'公共/受保护的组件,并且可以通过自己的属性和方法提供额外的功能。



继承的主题非常广泛,您应该可以使用google找到一个参考。


引用:

是什么让obj2特别优于obj1?

没什么。

In事实上你可以这样做:

 BaseClass obj1 =  new  BaseClass(); 
BaseClass obj2 = new ChildClass();
obj1 = obj2;



发生的事情 继承 - ChildClass继承自BaseClass,因此它是带有额外内容的基类 - 每个实例同时都是一个ChildClass实例和一个BaseClass实例。



想想汽车片刻:你可以驾驶一辆汽车。这意味着你可以驾驶福特和梅赛德斯;此外,您还可以驾驶福特嘉年华,福特福克斯,梅赛德斯A级和布加迪威龙 - 您无需为每个制造商或每个车型进行新的测试。

焦点继承自福特,继承自汽车

A级继承自梅赛德斯,继承自汽车。



所以汽车可以做任何事情(StartTheEngine,DriveToTheShops)任何福特都可以做,任何福克斯或嘉年华也可以做。



返回计算机,它是一样的:你有一个基类,所有派生类都可以做基本所能做的一切。当你使用变量时,它的类型决定了编译器允许你做什么:

 BaseClass obj1 =  new  BaseClass(); 
BaseClass obj2 = new ChildClass();
obj1.BaseClassMethod();
obj2.BaseClassMethod();

一切都很好。

但它不会让你使用ChildClass特定项目:

< pre lang =c#> obj1.ChildClassMethod();
obj2.ChildClassMethod();

两者都会给你一个编译器错误,因为obj1和obj2都能够持有一个BaseClass,这并不意味着他们持有的将是一个ChildClass实例。



这有意义吗?


课程



 public class Cat:Animal 
{
public int NumberOfBirdsKilled {get;组; }
public override string Speak()
{
returnMeow;
}
}

公共类Dog:Animal
{
public int NumberOfButtsSniffed {get;组; }
public override string Speak()
{
returnWoof;
}
}

公共类SockMaker
{
public void MakeSocks(动物)
{
for(int i = 1; i< = animal.NumberOfLegs; i ++)
{
Console.WriteLine(Making sock number+ i.ToString());
}
}
}





动物obj1 =新动物( ); 
Animal obj2 = new Cat();

// obj1引用基类Animal的一个实例,该实例只有Animal的特性,如NumberOfLegs或Speak()
// obj1变量是基类型Animal,所以只允许访问到NumberOfLegs或Speak()等动物属性
obj1.NumberOfLegs = 8;

// obj2引用子类Cat的实例,该实例同时具有Animal属性和Cat属性
// obj2变量属于基类型Animal,因此只允许访问Animal属性比如NumberOfLegs或Speak()

obj2.NumberOfLegs = 4;
// obj2.NumberOfBirdsKilled = 90001; < - 不会编译

//上面的行不能编译,因为即使obj2引用的对象有NumberOfBirdsKilled属性
// obj2变量本身只知道动物属性,这是一个Cat属性,而不是动物属性
//所以变量obj2引用的对象具有我们无法访问的属性,即使它们确实存在
//与obj1对比其中引用的对象是Animal,引用变量也是Animal
//所以我们可以访问对象的所有可能属性,没有任何东西被阻止

//因为obj2引用了Cat对象我们可以向上投射它到Cat

Cat c =(Cat)obj2;

//c和obj2引用相同的对象,但因为c变量是Cat类型,它知道Cat
//和Animal属性所以可以同时访问

Console.WriteLine(c.NumberOfLegs); //这将写为4,记住只有一个Cat对象,obj2和c都引用
c.NumberOfBirdsKilled = 9001; //此属性始终存在于对象上,但现在我们可以访问它,因为我们使用的是类型为Cat

的变量//为什么我们要这样做?假设我们有一个只关心Animal
List< Animal>上的属性的类。 animals = new List< Animal>();

animals.Add(new Cat {NumberOfLegs = 4,NumberOfBirdsKilled = 9001});
animals.Add(new Dog {NumberOfLegs = 4,NumberOfButtsSniffed = 7});

SockMaker sm = new SockMaker();

foreach(动物中的动物a)
{
//a可能引用猫,可能是狗,袜子制造商不关心因为它只对NumberOfLegs属性中的
//感兴趣所以只需要一个可以访问该属性的变量类型
sm.MakeSocks(a);
}


BaseClass obj1 = new BaseClass();
BaseClass obj2 = new ChildClass();


what makes the obj2 special over obj1?
if there is any scenario which can make obj2 special please quote the same.

What I have tried:

I have tried initializing object in both ways and using methods, parameters from it both looks similar only for me.

解决方案

A "child" class inherits it's base class' public/protected components, and can provide additional functionality via its own properties and methods.

The topic of inheritance is very broad, and you should probably find a reference using google.


Quote:

what makes the obj2 special over obj1?

Nothing.
In fact you can do this:

BaseClass obj1 = new BaseClass();
BaseClass obj2 = new ChildClass();
obj1 = obj2;


What's happening is inheritance - ChildClass inherits from BaseClass, so it is "Base class with extras" - every instance is both a ChildClass instance and a BaseClass instance at the same time.

Think about cars for a moment: You can drive a Car. Which means you can drive a Ford, and a Mercedes; and further you can drive a Ford Fiesta, and a Ford Focus, and a Mercedes A Class, and a Bugatti Veyron - you don't have to take a new test for each manufacturer or each model.
"Focus" inherits from "Ford", which inherits from "Car"
"A Class" inherits from "Mercedes", which inherits from "Car".

So anything that a Car can do (StartTheEngine, DriveToTheShops) any Ford can do, and any Focus or Fiesta can also do.

Back to computers, and it's the same thing: You have a base class and all derived classes can do everything that the base can. When you use the variable, it's type determines what the compiler will let you do:

BaseClass obj1 = new BaseClass();
BaseClass obj2 = new ChildClass();
obj1.BaseClassMethod();
obj2.BaseClassMethod();

All perfectly fine.
But it won't let you use ChildClass specific items:

obj1.ChildClassMethod();
obj2.ChildClassMethod();

Both will give you a compiler error because obj1 and obj2 are both capable of holding a BaseClass which doesn't mean that what they hold will be a ChildClass instance.

Does that make any sense?


Classes

public class Cat : Animal
{
    public int NumberOfBirdsKilled { get; set; }
    public override string Speak()
    {
        return "Meow";
    }
}

public class Dog : Animal
{
    public int NumberOfButtsSniffed { get; set; }
    public override string Speak()
    {
        return "Woof";
    }
}

public class SockMaker
{
    public void MakeSocks(Animal animal)
    {
        for (int i = 1; i <= animal.NumberOfLegs; i++)
        {
            Console.WriteLine("Making sock number " + i.ToString());
        }
    }
}



Animal obj1 = new Animal();
Animal obj2 = new Cat();

// obj1 references an instance of the base class Animal and that instance only has Animal properies like NumberOfLegs or Speak()
// the obj1 variable is of base type Animal so only allows access to Animal properties like NumberOfLegs or Speak()
obj1.NumberOfLegs = 8;

// obj2 references an instance of the child class Cat and that instance has both Animal properties and Cat properties
// the obj2 variable is of base type Animal so only allows access to Animal properties like NumberOfLegs or Speak()

obj2.NumberOfLegs = 4;
// obj2.NumberOfBirdsKilled = 90001; <-- won't compile

// the above line doesn't compile because even though the object referenced by obj2 has a NumberOfBirdsKilled property
// the obj2 variable itself only knows about Animal properties and that is a Cat property, not an Animal one
// so the object referenced by the variable obj2 has properties that we can't access even though they do exist
// contrast that with obj1 where the object referenced is Animal and the reference variable is also Animal
// so we can access all possible properties of the object, nothing is blocked off

// because obj2 references a Cat object we can "up cast" it to Cat

Cat c = (Cat)obj2;

// both "c" and "obj2" reference the same object but because the "c" variable is type Cat it knows about both Cat
// and Animal properties so can access both

Console.WriteLine(c.NumberOfLegs); // this will write "4", remember there is only one Cat object that both obj2 and c reference
c.NumberOfBirdsKilled = 9001; // this property always existed on the object, but now we can access it as we are using a variable of type Cat

// why would we want to do this?  Let's say we have a class that only cares about the properties on Animal
List<Animal> animals = new List<Animal>();

animals.Add(new Cat { NumberOfLegs = 4, NumberOfBirdsKilled = 9001 });
animals.Add(new Dog { NumberOfLegs = 4, NumberOfButtsSniffed = 7 });

SockMaker sm = new SockMaker();

foreach (Animal a in animals)
{
    // "a" might reference a "Cat", might be a "Dog", the sock maker doesn't care as it is only interested
    // in the NumberOfLegs property so only needs a variable type that can access that property
    sm.MakeSocks(a);
}


这篇关于在C#中使用基类和子类的基类实例之间的用途和区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆