简体   繁体   English

在不知道类型的情况下传递类的实例

[英]Passing instances of a class without knowing the Type

I want to know how to pass down instances of objects without knowing the Type that they are. 我想知道如何传递对象的实例而又不知道它们的类型。 I'd like to know this because if I have a 100 animal types, then I don't want to have a 100 if statements or a switch. 我想知道这一点,因为如果我有100种动物类型,那么我不想有100种if语句或开关。 I have provided a snippet, which is an example of what I want to basically achieve. 我提供了一个片段,这是我想要基本实现的一个示例。 Right now it obviously doesn't work where I put the comments at. 目前,我在其中发表评论的地方显然不起作用。

using System.IO;
using System;
using System.Collections.Generic;

class Program
{
    Dictionary<string, dynamic> myAnimals = new Dictionary<string, dynamic>();

    Program(){
        myAnimals.Add("Maggie", new Dog("Maggie"));
        myAnimals["Maggie"].bark();

        myAnimals.Add("Whiskers", new Cat("Whiskers"));
        myAnimals["Whiskers"].meow();

        animalClinic clinic = new animalClinic();
        clinic.cureAnimal(myAnimals["Whiskers"]);
    }

    static void Main()
    {
        new Program();
    }
}

class Dog{
    string name;

    public Dog(string n){
        name = n;
    }

    public void bark(){
        Console.WriteLine("\"Woof Woof\" - " + name);
    }
}

class Cat{
    string name;

    public Cat(string n){
        name = n;
    }

    public void meow(){
        Console.WriteLine("\"Meow Meow\" - " + name);
    }
}

class animalClinic(){
    public void cureAnimal(object animal){ //This is where I need some help.
        if(animal.name == "Maggie"){ //I know I can use 'animal.GetType() == ...' That isn't the point.
            Console.WriteLine("We heal fine dogs!"); //The point is to access various methods within the object.
        }else{//I know it kind of beats the point of Type-Safety, but this is only an example and another way to do this is perfectly fine with me.
            Console.WriteLine("Eww a cat!")
        }
    }
}

If anyone knows an alternative solution to this, then please go ahead and share! 如果有人知道替代解决方案,请继续分享!

Thanks. 谢谢。

EDIT: I think you'll also need to reference the animal instead of just passing it down. 编辑:我认为您还需要引用动物,而不只是将其传递下去。

This is what polymorphism is for: 这就是多态性的目的:

public interface IAnimal
{
     string name {get;set;}

     void speak();

     void cure();
}

public class Dog : IAnimal
{
    public Dog (string n)
    {
        name = n;
    }

    public string name {get;set;}

    public void bark() 
    {
        Console.WriteLine("\"Woof Woof\" - " + name);
    }

    public void speak() { bark(); }

    public void cure()
    { 
         Console.WriteLine("We heal fine dogs!"); 
    }
}

public class Cat : IAnimal
{
    public Cat(string n)
    {
        name = n;
    }

    public string name {get;set;}

    public void meow() 
    {
        Console.WriteLine("\"Meow Meow\" - " + name);
    }

    public void speak() { meow(); }

    public void cure()
    { 
         Console.WriteLine("Eww a cat!"); 
    }
}

class Program
{
    static Dictionary<string, IAnimal> myAnimals = new Dictionary<string, IAnimal>();

    static void Main()
    {
        myAnimals.Add("Maggie", new Dog("Maggie"));
        myAnimals["Maggie"].speak();

        myAnimals.Add("Whiskers", new Cat("Whiskers"));
        myAnimals["Whiskers"].speak();

        animalClinic clinic = new animalClinic();
        clinic.cureAnimal(myAnimals["Whiskers"]);
    }
}

public class animalClinic
{
    public void cureAnimal(IAnimal animal)
    { 
        animal.cure();
    }
}

Create an interface (contains definitions for a group of related functionalities that a class or a struct can implement) called IAnimal which contains a Description property which returns "We heal fine dogs!" 创建一个名为IAnimal接口 (包含一个类或结构体可以实现的一组相关功能的定义),该接口包含一个Description属性,该属性返回“ We heal fine dogs!” for your Dog class etc. Each of your concrete animal classes implement this interface meaning you can just call the Description property in your cureAnimal method. 用于您的Dog类等。每个具体的动物类都实现此接口,这意味着您可以只在cureAnimal方法中调用Description属性。

Use polymorphism . 使用多态

public abstract class Animal
{
    public string Name { get; set; }

    public abstract void Cure();
}

public class AnimalClinic
{
    public void CureAnimal(Animal animal)
    {
        animal.Cure();
    }
}

public class Dog : Animal
{
    public override void Cure()
    {
        Console.WriteLine("We heal fine dogs!");
    }
}

If you want to define the Cure logic inside of the AnimalClinic class like you do now, you might have to perform conditional execution of some sort . 如果要像现在一样在AnimalClinic类中定义Cure逻辑,则可能必须执行某种条件执行。

This conditional execution does not have to be as unwieldy as a massive if statement or even a switch . 有条件的执行不必像大量的if语句甚至是switch那样笨拙。 You can research alterantive solutions to if statements here on SO. 您可以在SO上研究if语句的替代解决方案。 In fact, Joel Coehoorn has supplied one. 实际上,乔尔·科恩(Joel Coehoorn)提供了一个。

I believe the best option here is to use the strategy design pattern. 我相信这里最好的选择是使用策略设计模式。 Perfectly explained here http://www.dofactory.com/net/strategy-design-pattern 在这里完美解释http://www.dofactory.com/net/strategy-design-pattern

An example for your case is provided by ByteBlast and Joel Coehoorn's answers ByteBlast和Joel Coehoorn的答案提供了您的案例的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在不知道类型的情况下引用泛型类型的实例 - Referencing instances of Generic Type without knowing the Type 在不知道类型的情况下构造通用 class - Construct Generic class without knowing type 在不知道类型的情况下反序列化Json - Deserialize Json without knowing type 不知道类型就返回通用 - Returning generic without knowing type 如何在不知道类型的情况下转换泛型类型 - How to cast a generic type without knowing the type 在不知道类型的情况下使用泛型类型转换 object - Cast an object with a generic type without knowing the type 泛型-将实例作为基本类型传递 - Generics - Passing instances as a base type 如何在不知道typeparam类型的情况下检查对象是否从通用基类继承 - How to check if object inherits from a generic base class without knowing type of typeparam 如何在不事先知道类型的情况下使用XmlSerializer反序列化可能是基类或派生类的对象? - How do I use an XmlSerializer to deserialize an object that might be of a base or derived class without knowing the type beforehand? 如何在不知道泛型的情况下获取泛型类(单例)中静态字段的值 - How to get the value of a static field in a generic class (singleton) without knowing the generic type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM