使用变量检查类是否为类型
本文关键字:是否 类型 检查 变量 | 更新日期: 2023-09-27 18:32:50
我正在尝试查看是否可以在比较中使用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"和"设备类型"拉出错误"找不到类型或命名空间名称'tmp'(您是否缺少使用指令或程序集引用?
我知道这通常是通过说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()
来确定实例的类型。