[英]Checking if class is a type using a variable?
我试图看看是否可以在比较中的变量中使用System.Type。我有以下代码:
internal ObservableCollection<FREQUENCY> GetFrequencies(System.Type equipmenttype)
{
...
foreach (var incident in query)
{
if (typeof(equipmenttype).IsSubclassOf(typeof(incident)))
{
foreach (var freq in incident.FREQUENCY)
{
freqs.Add(freq);
}
}
}
return freqs;
}
但是变量'tmp'和'equipmenttype'发出错误“找不到类型或名称空间名称'tmp'(您是否缺少using指令或程序集引用?)”
我知道通常通过说typeof(MYCLASS)来使用它,但是我很好奇是否可以使用System.Type变量来实现,或者是否有任何方法可以做到这一点。 谢谢。
我看不到您的代码中tmp
在哪里。 但请确保您错过了
if (typeof(equipmenttype).IsSubclassOf(typeof(incident)))
应该
if (equipmenttype.IsSubclassOf(incident.GetType()))
typeof
运算符用于获取Type的RuntimeType
。 但是您已经在这里获得了RuntimeType
,它是equipmenttype
,因此您无需在此处使用typeof
。
尝试if (equipmenttype.IsSubclassOf(incident.GetType())
。 equipmenttype
已经是System.Type
,并且必须调用GetType()
以确定实例的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.