使用c#的基本对象引用和使用问题

发布于 2024-10-09 08:49:09 字数 1107 浏览 1 评论 0原文

我是面向对象和编程领域的新手。有些事情我仍在努力理解。

例如,我有以下代码:

 public abstract class ParentA
    {
        public virtual void MethodA()
        {
            Console.WriteLine("Doing somethin...");
        }
    }
    public class DerivedClassA : ParentA
    {
        public override void MethodA()
        {
            Console.WriteLine("Doing something from derived...");
        }
    }

现在,我看到一些代码,其中类的实例化如下:

ParentA p = new DerivedClassA();
            p.MethodA();

为什么不直接实例化您想要使用的实际类并使用它的成员?

 DerivedClassA d = new DerivedClassA();
            d.MethodA();

我看到这也使用了很多接口,其中是这样写的:

public interface Animal
    {
        void Bark();
    }
    public class Dog : Animal
    {
        public void Bark()
        {
            Console.WriteLine("bark");
        }
    }

然后以这种方式使用:

Animal a = new Dog();
            a.Bark();

为什么不这样做?:

Dog d = new Dog();
            d.Bark();

什么时候重要?

感谢您的帮助

:)

I am new the realm of Object Orientation and programming. There are some things I am still trying to understand.

For instance, I have the following code:

 public abstract class ParentA
    {
        public virtual void MethodA()
        {
            Console.WriteLine("Doing somethin...");
        }
    }
    public class DerivedClassA : ParentA
    {
        public override void MethodA()
        {
            Console.WriteLine("Doing something from derived...");
        }
    }

Now, I see some code where the class is instatiated like this:

ParentA p = new DerivedClassA();
            p.MethodA();

Why not just instatiate the actually class you want to use and use it's members?

 DerivedClassA d = new DerivedClassA();
            d.MethodA();

I see this used a lot interfaces as well where is written like this:

public interface Animal
    {
        void Bark();
    }
    public class Dog : Animal
    {
        public void Bark()
        {
            Console.WriteLine("bark");
        }
    }

and then used in this manner:

Animal a = new Dog();
            a.Bark();

Why not just do this??:

Dog d = new Dog();
            d.Bark();

When does it matter?

Thanks for the help

:)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

乜一 2024-10-16 08:49:09

你说得对;这看起来确实很奇怪,不是吗?

代码:

Animal animal = new Dog();

相当罕见;通常,如果您知道自己正在创建一只 Dog,那么您会将变量键入为 Dog。更常见的是:

Animal animal = petStore.ObtainInexpensivePet();

你不知道具体会返回什么;也许是一只小猫,也许是一只鬣蜥,但你知道它至少会是一只动物。创建狗对象的是宠物店,而不是你。

You're right; that does look odd, doesn't it?

The code:

Animal animal = new Dog();

is reasonably rare; normally if you knew you were making a Dog then you'd type the variable as Dog. What is more common is:

Animal animal = petStore.ObtainInexpensivePet();

where you don't know exactly what is going to come back; maybe a kitten, maybe an iguana, but you know it will at least be an Animal. It's the pet store that is creating the dog object, not you.

黯淡〆 2024-10-16 08:49:09

该技术可用于确保代码不耦合到特定的实现。

如果这个特定的派生类具有其他方法(例如,List),并且您希望确保您的代码可以与没有这些额外方法的其他实现一起使用,请将变量声明为基本类型将确保您不会调用这些方法。

This technique can be used to make sure that the code is not coupled to a specific implementation.

If this particular derived class has additional methods (eg, List<T>), and you want to ensure that your code will work with other implementations that don't have these extra methods, declaring the variable as the base type will ensure that you don't call the methods.

月下客 2024-10-16 08:49:09

调用 a.Bark 与 d.Bark 的目的是让您不需要知道对象的实际类型。通常,当您处理动物列表时,或者如果您正在编写一种将动物作为参数或返回动物的方法,但您不想使该方法特定于 Dog 类型对象时,您会看到这种情况。

查找一些有关多态性的信息,这应该可以帮助您更好地理解。

The purpose behind calling a.Bark vs. d.Bark is so that you don't need to know the actual type of the object. Typically you would see this when you were dealing with a list of Animals or if you were writing a method that took an animal as a parameter or returned one but you didn't want to make the method specific to Dog type objects.

Look up some info on polymorphism that should help you get a better understanding.

檐上三寸雪 2024-10-16 08:49:09

这个概念被称为“编程到接口而不是实现”,这里接口并不意味着实际的C#接口,它可以是基类、抽象类,这是OO世界中非常流行的概念是“依赖注入”、“IOC(控制反转)”等其他概念的基础,

就像 Eric 已经说过的那样,

如果您提前知道您实际上将创建一个 Dog 对象,那么比使用基于 Interfaced 的技术影响较小,但它当您使用返回 Animal 的 Factory 方法时,真正的力量就出现了,并且您实际上直到运行时都不知道具体类型。

This concept is called 'Programe to an interface not to an implementation' , here interface does not mean actual c# interface it can be a base class , abstract class and it is a very popular concept in OO world which is a base for other concepts like 'Dependency Injection' , 'IOC (Inversion of Control)'

Like Eric already stated that

if you know in Advance that you are actually going to create a Dog object than using Interfaced based technique is less impact BUT its actual power comes when you use a Factory method which returns a Animal and you actually till Runtime does not know the concrete type.

蓝天 2024-10-16 08:49:09

您所看到的是继承的另一面。继承不仅仅是让您自己重写另一个类中存在的功能。

这个想法是,如果正确设计类层次结构,则可以在整个代码中以更安全的方式使用类(由于 C# 是强类型的)。当然,重用可能用于整个对象系列的代码,而不是为每个类重写它。

让我们分析一下您给我们的例子的强度。

因为您有一个名为 Animal 的已知接口,所以您不需要知道整个程序中存在的所有动物类型(实现该接口的类)。

这允许您编写如下代码:

public interface Animal
    {
        void Play();
        void WagTale();
        void Eat(Food food);
    }
}


void PlayWithAnimal(Animal animal) {
   animal.WagTale();
   this.ThrowBall();
   animal.Play();
   animal.WaTale();
}

对于实现该接口的任何其他动物类,无论它是如何实现的,它的工作原理都是一样的。

因此,您可以这样调用该方法:

Dog dog = new Dog();
Lion lion = new Lion();
Flee flee = new Flee();
PlayWithAnimal(dog);
PlayWithAnimal(lion);
PlayWithAnimal(flee);

同样,这个想法是能够对您的类进行分类,并使用在代码中使用相同方法和成员的最基本元素。

一个更面向 C# 的示例:Image 是一个抽象类,您甚至无法创建此类对象的实例。但是还有许多其他类派生自 Image,因此,尽管没有对象可以是真正的 Image,但您大部分都会看到 Image在使用图像的代码中。 (同样,大多数图像实际上是 Bitmap 或其他一些类)

What you're seeing is the other side of inheritance. Inheritance is not just saving yourself rewriting features that exist in another class.

The idea is that if you design the class hierarchy properly, you can use your classes in a safer way throughout your code (Thanks to the fact that C# is strongly typed). And of course re-use code that might be used for a whole family of objects, rather then rewrite it for each class.

Lets analyze the strength of the example you gave us.

Because you have a known Interface called Animal, you don't need to know all the animal types that exist throughout the program (classes that implement the interface).

This allows you to make code like this:

public interface Animal
    {
        void Play();
        void WagTale();
        void Eat(Food food);
    }
}


void PlayWithAnimal(Animal animal) {
   animal.WagTale();
   this.ThrowBall();
   animal.Play();
   animal.WaTale();
}

This will work just the same for any other animal class that implements that interface, no matter how it's implemented.

So you can call the method like this:

Dog dog = new Dog();
Lion lion = new Lion();
Flee flee = new Flee();
PlayWithAnimal(dog);
PlayWithAnimal(lion);
PlayWithAnimal(flee);

Again, the idea is to be able to categorize your classes and use the most basic elements that use the same methods and members in your code.

A more C# oriented example: Image is an abstract class, you can't even create an instance of such an object. But there are a lot of other classes that derive from Image, so although no object can be a real Image, you'll mostly see Image in code that uses Images. (Again mostly the image actually be Bitmap or some other class)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文