Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.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#,这是一个非常奇怪的问题,真的让我很紧张。我正在制作一个简单的C#ServicesManager类。但我遇到这个问题完全没有明显的原因。无论如何,这里是有问题的函数: /// <summary> /// This function checks if the ServicesManager contains a service of the specified type or not. /// </summary> /// <param

这是一个非常奇怪的问题,真的让我很紧张。我正在制作一个简单的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;
    }
//
///此函数用于检查ServicesManager是否包含指定类型的服务。
/// 
///要检查的服务类型。
///如果找到指定类型的服务,则为True,否则为false。
公共bool包含(类型serviceType)
{
布尔结果=假;
类型t=服务类型;
foreach(ISE_服务在m_服务列表中)
{
如果(s)是服务类型
{
结果=真;
打破
}
}
返回结果;
}
ISE_服务只是一个表示服务类的接口。上述函数只是检查ServicesManager中是否已经存在指定类型的服务

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

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

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

您需要这样做:

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

询问
s
是否为类型
serviceType
,其中
serviceType
为特定类型。当然,它不是一种特定的类型;它是一个
类型的变量

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

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

是的,因为“类型”这个词有多种用法,所以它令人困惑


从根本上讲,它归结为编译时类型之间的差异,编译时类型在代码中由类型的名称表示(例如
string
int
MyType
)还有一种运行时类型,它由名为
type

的类的实例表示。这到底是微软的错吗?你没有重新编码ServiceLocator吗?如果您使用
foreach
迭代通过
m_服务列表
,是否存在
iseu服务
可能实际为空的场景?啊,我试过一次,但它仍然在同一点下划线并显示错误。但那是因为我仍然尝试使用is运算符而不是==。但是如果我把它改成像你展示的那样使用==的话,它就可以工作了。谢谢大家!@Puuskis当然可以。如果
m_ServicesList
是引用类型的数组或列表,则其任何元素都可以为null。AddService函数将在将值添加到列表中之前确保该值不为null。一旦添加了一个,它将一直保留到程序关闭为止。@Michaelfontani可能是这样,但您发布的代码没有定义
m\u ServicesList的类型,因此我的答案不得不放在安全的一边。:)
object.GetType(); // Returns a variable of type `Type`
typeof(MyTypeName); // Returns a variable of type `Type`