gpt4 book ai didi

C# 运算符 'is' 参数

转载 作者:太空狗 更新时间:2023-10-30 00:07:13 25 4
gpt4 key购买 nike

我正在开发一个小游戏,只是为了好玩,我偶然发现了一个与 C# 的 is 运算符有关的困惑时刻。这是代码:

public static InventorySlot FindSlotWithItem(this IInventory inventory, Type itemType)
{
return inventory.InventorySlots.FirstOrDefault(t => t is itemType);
}

目前,这段代码无法编译,因为我的 Visual Studio 告诉我找不到类型或命名空间名称“itemType”。我想知道为什么会这样,并在 MSDN 上查找了一些信息。这是我发现的:

is (C# Reference): Checks if an object is compatible with a given type. For example, the following code can determine if an object is an instance of the MyObject type, or a type that derives from MyObject

这些行让我更加困惑,因为我显然将一个对象作为第一个参数传递,将类型作为第二个参数传递。我知道这与编译器查找名为“itemType”的类型这一事实有关,但这并不是我想要的行为。

请告诉我为什么这样的语法不起作用以及为什么 'itemType' 不被 'is' 运算符视为类型。

最佳答案

这里的问题是 Type 类的对象与类的编译时常量引用不同。相反,Type 对象只是封装类元数据的对象,因此它们不能用于直接创建变量、调用静态成员、作为泛型传递或使用 is 调用 实际类引用的方式。

也就是说,上述所有操作都有仅使用元数据的变通方法。对于类型比较,尝试

t => itemType.IsAssignableFrom(t.GetType());

这将检查“itemType 类型的变量是否可以分配 t.GetType() 类型的值”——这不仅会检查输入,还会检查也将毫无怨言地很好地接受多态类型。

关于C# 运算符 'is' 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com