C# 检查类是否是使用变量的类型?
我正在尝试查看是否可以使用系统。在比较中键入一个变量。我有以下代码:C# 检查类是否是使用变量的类型?,c#,C#,我正在尝试查看是否可以使用系统。在比较中键入一个变量。我有以下代码: internal ObservableCollection<FREQUENCY> GetFrequencies(System.Type equipmenttype) { ... foreach (var incident in query) { if (typeof(equipmenttype).IsSubclassOf(t
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;
}
内部可观测采集频率(System.Type equipmenttype)
{
...
foreach(查询中的var事件)
{
if(设备类型)。IsSubclassOf(事件类型)
{
foreach(事件中的var频率。频率)
{
增加频率(freq);
}
}
}
返回频率;
}
但是变量“tmp”和“equipmenttype”导致错误“找不到类型或命名空间名称“tmp”(是否缺少using指令或程序集引用?)
我知道这通常是通过说typeof(MYCLASS)来使用的,但是我很好奇这是否可以使用System.Type变量,或者是否有任何方法来实现。谢谢。请尝试
if(equipmenttype.IsSubclassOf(incident.GetType())
equipmenttype
已经是一个系统。Type
,必须调用GetType()
来确定实例的类型。请尝试if(equipmenttype.IsSubclassOf(incident.GetType())
equipmenttype
已经是一个系统。必须调用Type
,和GetType()
来确定实例的类型。我看不到tmp
在您的代码中的位置。但请确定您缺少了这个
if (typeof(equipmenttype).IsSubclassOf(typeof(incident)))
应该是
if (equipmenttype.IsSubclassOf(incident.GetType()))
typeof
操作符用于获取类型的RuntimeType
。但是您已经在这里获得了RuntimeType
,这就是equipmenttype
,因此您不需要在这里使用typeof
。我看不到tmp
在您的代码中的什么地方。但是您肯定错过了这个
if (typeof(equipmenttype).IsSubclassOf(typeof(incident)))
应该是
if (equipmenttype.IsSubclassOf(incident.GetType()))
typeof
运算符用于获取类型的RuntimeType
。但是您已经在这里获得了RuntimeType
,即equipmenttype
,因此您不需要在这里使用typeof
。我不相信typeof(事件)
将编译,因为它是引用,而不是类型。它应该是incident.GetType()
。看看反射API:我不相信typeof(incident)
将编译,因为它是引用,而不是类型。它应该是incident.GetType()
。看看反射API:这很有道理。非常感谢!我以前从未尝试过类似的方法。这很有道理。非常感谢!我以前从未尝试过类似的方法。