【问题标题】:Checking if class is a type using a variable?检查类是否是使用变量的类型?
【发布时间】:2013-09-25 16:09:22
【问题描述】:

我正在尝试查看是否可以在比较中在变量中使用 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 的变量,或者是否有任何方法可以做到这一点。谢谢。

【问题讨论】:

标签: c#


【解决方案1】:

我在你的代码中看不到tmp 的位置。但确定你错过了这个

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

应该是

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

typeof 运算符用于获取类型的RuntimeType。但是你这里已经有了RuntimeType,也就是equipmenttype,所以你不需要在这里使用typeof

【讨论】:

  • 这是有道理的。非常感谢!我以前从未尝试过这样的事情。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 2011-07-09
    • 2010-12-25
    • 1970-01-01
    • 2014-07-19
    相关资源
    最近更新 更多