简体   繁体   English

检查类是否是使用变量的类型?

[英]Checking if class is a type using a variable?

I am trying to see if it is possible to use a System.Type in a variable in a comparison.I have the following code: 我试图看看是否可以在比较中的变量中使用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;
    }

But the variables 'tmp' and 'equipmenttype' pull the error "The type or namespace name 'tmp' could not be found (are you missing a using directive or an assembly reference?)" 但是变量'tmp'和'equipmenttype'发出错误“找不到类型或名称空间名称'tmp'(您是否缺少using指令或程序集引用?)”

I understand that usually this is used by saying typeof(MYCLASS), but I was curious if this was possible using a variable of System.Type, or if there was any way to do that. 我知道通常通过说typeof(MYCLASS)来使用它,但是我很好奇是否可以使用System.Type变量来实现,或者是否有任何方法可以做到这一点。 Thanks. 谢谢。

I can't see where is tmp in you code. 我看不到您的代码中tmp在哪里。 but sure you're missing this 但请确保您错过了

if (typeof(equipmenttype).IsSubclassOf(typeof(incident)))

Should be 应该

if (equipmenttype.IsSubclassOf(incident.GetType()))

typeof operator is used to get the RuntimeType of a Type. typeof运算符用于获取Type的RuntimeType But you already got RuntimeType here which is equipmenttype , So you don't need to use typeof here. 但是您已经在这里获得了RuntimeType ,它是equipmenttype ,因此您无需在此处使用typeof

尝试if (equipmenttype.IsSubclassOf(incident.GetType())equipmenttype已经是System.Type ,并且必须调用GetType()以确定实例的类型。

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

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