gpt4 book ai didi

c# - 将对象转换为其他对象的类型

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:58 27 4
gpt4 key购买 nike

如果我有一个将任何对象作为参数的方法,我想创建另一个相同类型的对象。换句话说,如果我有一个 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 keword 的真正好处。我知道它很有用,但我只是用它来使我的代码更小、更易读……但在这种情况下,它真的很有帮助!

最佳答案

像这样:

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

(实际上并没有测试)

关于c# - 将对象转换为其他对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8434640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com