繁体   English   中英

(“儿童班”是“父母班”)

[英](“Child Class” is “Parent class”)

我正在上HotDog班,还是Food班的孩子。

public class HotDog : Food
{
    public HotDog () : base ("hotdog", new string[] { "bread", "meat"}, new int[] { 1, 1 }, 0.7)
    {
    }
}

我试图做到这一点

Type t = typeof("HotDog");
if (t is Food) {
    Food f = (Food)Food.CreateOne (t);
}

这是我的CreateOne方法

public static Consumables CreateOne (Type t)
{
    return (Consumables)Activator.CreateInstance (t);
}

但是我得到一个错误,即t永远不是所提供的Food类型的,因此里面的代码无法访问。 知道这东西怎么了,我该如何解决?

你有没有尝试过

 Type t = typeof(HotDog)

另请参阅类型检查:typeof,GetType还是is?

您需要反射才能使它起作用。

首先获取实际类型的HotDog:

Type t = Type.GetType("MyNamespace.HotDog");

现在创建这种类型的新实例:

HotDog instance = (HotDog) Activator.CreateInstance(t);

请注意,这将调用默认构造函数。 如果需要参数化,请使用Activator#CreateInstance(t, object[])

据我所知,问题在于您的if陈述。

Type t = typeof(...);
if (t is Food) { ... }

is运算符检查左表达式的类型是否为右表达式的有效值。

换句话说,您正在检查t的类型(即Type )对于Food类是否是有效值,当然不是。

您可以使用Type.IsAssignableFrom

if (typeof(Food).IsAssignableFrom(t)) { ... }

IsAssignableFrom确定是否可以将类型t的实例分配给typeof(Food)类型的变量,即,如果返回true,则可以执行

Hotdog h;
Food f;

if (typeof(Food).IsAssignableFrom(typeof(Hotdog))
{
    f = h; // you can assign a Hotdog to a Food
}

// this would return false for your classes
if (typeof(Hotdog).IsAssignableFrom(typeof(Food))
{
    h = f; // you can assign a Food to a Hotdog
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM