函数内部找不到函数参数

时间:2013-06-24 11:15:03

标签: c#

这是一个非常奇怪的问题,让我感到紧张。我有一个简单的C#ServicesManager类。但是,除了微软是愚蠢的以外,我完全没有明显的理由得到这个问题(我作为一名程序员的年代已经使我极其愚蠢地说服了他)。无论如何,这是有问题的功能:

    /// <summary>
    /// This function checks if the ServicesManager contains a service of the specified type or not.
    /// </summary>
    /// <param name="serviceType">The type of service to check for.</param>
    /// <returns>True if a service of the specified type is found, or false otherwise.</returns>
    public bool Contains(Type serviceType)
    {
        bool result = false;
        Type t = serviceType;


        foreach (ISE_Service s in m_ServicesList)
        {
            if (s is serviceType)
            {
                result = true;
                break;
            }

        }


        return result;
    }

ISE_Service只是一个代表服务类的接口。上面的函数只是检查ServicesManager中是否已存在指定类型的服务。

错误列表显示以下错误,并始终在if语句中突出显示带有红色波浪线的“serviceType”:

  

错误3找不到类型或命名空间名称'serviceType'(您是否缺少using指令或程序集引用?)C:\ MegafontProductions \ SpiritEngine \ SpiritEngine \ Source \ ApplicationLayer \ ServicesManager.cs 55

这个错误毫无意义。这是这个功能的参数。据我所知,这个问题要么是由is关键字引起的,要么是由Type类型引起的。如您所见,在循环上方访问参数serviceType就好了。那么它是如何在if语句中突然找不到的呢?

1 个答案:

答案 0 :(得分:2)

你需要这样做:

if ((s != null) && (s.GetType() == serviceType))

什么

if (s is serviceType)

确实询问sserviceType类型serviceType是哪种类型。当然,它不是特定类型;它是Type类型的变量。

Type是一个表示类型信息的类,可以通过以下方式获取:

object.GetType(); // Returns a variable of type `Type`

或者:

typeof(MyTypeName); // Returns a variable of type `Type`

是的,由于多次使用“类型”这个词,这很令人困惑。

从根本上说,它归结为编译时类型之间的区别,它在代码中由类型名称(例如stringintMyType)和运行时类型,由名为Type的类的实例表示。

相关问题