Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查类是否是使用变量的类型?_C# - Fatal编程技术网

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:这很有道理。非常感谢!我以前从未尝试过类似的方法。这很有道理。非常感谢!我以前从未尝试过类似的方法。