将对象转换为其他对象的类型

发布于 2024-12-20 06:41:59 字数 2659 浏览 2 评论 0原文

如果我有一个将任何对象作为参数的方法,我会想创建另一个相同类型的对象。换句话说,如果我有一个 Person 类型的对象,我想强制转换或实例化一个 Person 类型的新对象。另一方面,如果该对象是 Animal,我想从该类实例化一个新对象。所有这一切都无需使用 if 或 switch 语句。让我告诉你我的意思

   class Animal {

        public virtual void Talk()
        {
            Console.WriteLine("-");
        }
    }
    class Dog :Animal
    {
        public override Talk()
        {
            Console.WriteLine("Woof");
        }
    }
    class Cat : Animal
    {
        public override void Talk()
        {
            Console.WriteLine("Miau");
        }
    }

    public static void Main(String[] args)
    {

        Animal a = generateRandomAnimal();

        Animal b;  // I want to institate object b without needing an if statement or a switch            


        // I want to avoid this...
        if (a is Dog)
            b = new Dog();
        else if (a is Cat)
            b = new Cat();
        else
            b = new Animal();

        // if I new what b would be a Cat in advance i know I could do :

        b = (Cat)b; 


        // if am looking for something like

        b=(a.GetType())b; // this gives a compile error

    }

    static Animal generateRandomAnimal()
    {
        switch (new Random().Next(1, 4))
        {
            case 1:
                return new Animal();
            case 2:
                return new Dog();
            default:
                return new Cat();
        }            
    }

编辑

感谢kprobst我最终得到:

    class Person
    {

        public string Address { get; set; }
        public string Name { get; set; }

    }

    class Animal
    {
        public virtual void Talk()
        {
            Console.WriteLine("-");
        }
    }

    class Car
    {
        public int numberOfDoors { get; set; }
    }


    static object generateRandomObject()
    {
        switch (new Random().Next(1, 4))
        {
            case 1:
                return new Person();
            case 2:
                return new Car();
            default:
                return new Animal();
        }
    }

    public static void Main(String[] args)
    {

        object o = generateRandomObject();

        object newObject;  // i want new object to be of the same type as object o


        if (o is Animal)
            newObject = new Animal();
        if (o is Person)
            newObject = new Person();
        if (o is Car)
            newObject = new Car();


        Type t = o.GetType();
        var b = Activator.CreateInstance(t);
        //.....etc

在我的示例中并非所有对象都继承自同一个类。这是我第一次看到 var 关键字的真正好处。我知道它很有帮助,但我只是用它来使我的代码更小、更具可读性……但在这种情况下,它真的很有帮助!

If I have a method that takes any object as a parameter I will like to create another object of the same type. In other words if I have an object of type Person I will like to cast or instantiate a new object of type person. If that object is an Animal in the other hand I will like to instantiate a new object from that class. All this without using an if or switch statement. let me show you what I mean

   class Animal {

        public virtual void Talk()
        {
            Console.WriteLine("-");
        }
    }
    class Dog :Animal
    {
        public override Talk()
        {
            Console.WriteLine("Woof");
        }
    }
    class Cat : Animal
    {
        public override void Talk()
        {
            Console.WriteLine("Miau");
        }
    }

    public static void Main(String[] args)
    {

        Animal a = generateRandomAnimal();

        Animal b;  // I want to institate object b without needing an if statement or a switch            


        // I want to avoid this...
        if (a is Dog)
            b = new Dog();
        else if (a is Cat)
            b = new Cat();
        else
            b = new Animal();

        // if I new what b would be a Cat in advance i know I could do :

        b = (Cat)b; 


        // if am looking for something like

        b=(a.GetType())b; // this gives a compile error

    }

    static Animal generateRandomAnimal()
    {
        switch (new Random().Next(1, 4))
        {
            case 1:
                return new Animal();
            case 2:
                return new Dog();
            default:
                return new Cat();
        }            
    }

Edit

Thanks to kprobst I ended up with:

    class Person
    {

        public string Address { get; set; }
        public string Name { get; set; }

    }

    class Animal
    {
        public virtual void Talk()
        {
            Console.WriteLine("-");
        }
    }

    class Car
    {
        public int numberOfDoors { get; set; }
    }


    static object generateRandomObject()
    {
        switch (new Random().Next(1, 4))
        {
            case 1:
                return new Person();
            case 2:
                return new Car();
            default:
                return new Animal();
        }
    }

    public static void Main(String[] args)
    {

        object o = generateRandomObject();

        object newObject;  // i want new object to be of the same type as object o


        if (o is Animal)
            newObject = new Animal();
        if (o is Person)
            newObject = new Person();
        if (o is Car)
            newObject = new Car();


        Type t = o.GetType();
        var b = Activator.CreateInstance(t);
        //.....etc

In my example not all objects inherited from the same class. It is the first time I see the a real benefit from the var keword. I know it is helpful but I just have use it to make my code smaller and more readable... but in this case it really helps out!

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

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

发布评论

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

评论(5

风苍溪 2024-12-27 06:41:59

像这样的东西:(

Type t = a.GetType();
Animal b = (Animal) Activator.CreateInstance(t);

实际上没有测试过)

Something like this:

Type t = a.GetType();
Animal b = (Animal) Activator.CreateInstance(t);

(didn't actually test that)

后eg是否自 2024-12-27 06:41:59

如果我处于你的位置,我会实现 IClonable 接口并调用:

Animal b = a.Clone();

If I were in your shoes, I would implement the IClonable interface and just call :

Animal b = a.Clone();
神爱温柔 2024-12-27 06:41:59

您可以创建一个名为“CreateNew()”的方法并创建当前对象类型的空实例。您可以通过将该方法设为虚拟或使用以下方法来实现此目的:

public Animal CreateNew() 
{
    return (Type)Activator.CreateInstance(GetType());
}

You could create a method called "CreateNew()" and create a empty instance of the current object type. You can do this by making the method virtual or use this approach:

public Animal CreateNew() 
{
    return (Type)Activator.CreateInstance(GetType());
}
森末i 2024-12-27 06:41:59

只需在 Animal 上有一个可重写的方法,称为 Duplicate() 或其他方法,然后返回一个新实例。

例如:

class Animal //should this class really be abstract?
{
    public virtual void Talk()
    {
        Console.WriteLine("-");
    }

    public virtual Animal Duplicate()
    {
        return new Animal(); 
    }
}
class Dog : Animal
{
    public override void Talk()
    {
        Console.WriteLine("Woof");
    }

    public override Animal Duplicate()
    {
        return new Dog();
    }
}
class Cat : Animal
{
    public override void Talk()
    {
        Console.WriteLine("Miau");
    }

    public override Animal Duplicate()
    {
        return new Cat();
    }
}

另外,请注意 Talk() 方法的更改,将其设为虚拟,然后在子类中重写它。

Just have an overridable method on Animal called Duplicate() or something, and return a new instance.

For example:

class Animal //should this class really be abstract?
{
    public virtual void Talk()
    {
        Console.WriteLine("-");
    }

    public virtual Animal Duplicate()
    {
        return new Animal(); 
    }
}
class Dog : Animal
{
    public override void Talk()
    {
        Console.WriteLine("Woof");
    }

    public override Animal Duplicate()
    {
        return new Dog();
    }
}
class Cat : Animal
{
    public override void Talk()
    {
        Console.WriteLine("Miau");
    }

    public override Animal Duplicate()
    {
        return new Cat();
    }
}

Also, please note the change for the Talk() method, by making it virtual and then overriding it in the sub classes.

不…忘初心 2024-12-27 06:41:59

你不能那样做“动态类型转换”。

我建议使用一些面向对象的编程。尝试在继承 Animal

: In Animal:

public abstract Animal GenerateAnimal();

In Cat:

public override Animal GenerateAnimal()
{
    return new Cat();
}

In Dog 的每个类中实现以下方法:

public override Animal GenerateAnimal()
{
    return new Dog();
}

You can't do "dynamic type-casting" like that.

I would suggest using a bit of object oriented programming. Try implementing the following method in every class that inherits from Animal:

In Animal:

public abstract Animal GenerateAnimal();

In Cat:

public override Animal GenerateAnimal()
{
    return new Cat();
}

In Dog:

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