C # operator are arguments

I am developing a little game for fun, and I came across a confusing moment when C # is an operator. Here is the code:

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

Be that as it may, this code does not compile since my Visual Studio tells me that the type or namespace name 'itemType' could not be found. I was wondering why this is so, and was looking for some information on MSDN. And here is what I found:

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

And these lines confused me even more, because I explicitly pass the object as the first parameter, and the type as the second. I understand that this is due to the fact that the compiler is looking for a type named "itemType", but this is not exactly the behavior I want.

Please tell me why this syntax does not work and why 'itemType' is not considered a type by the 'is' operator.

+4
source share
3 answers

, Type . Type - , , , , generics is .

, .

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

, itemType t.GetType() "- , .

+6

:

public static InventorySlot FindItem<T>(this IInventory inventory)
{
    return inventory.InventorySlots.FirstOrDefault(t => t is T);
}

:

public static InventorySlot FindItem(this IInventory inventory, Type itemType)
{
    return inventory.InventorySlots.FirstOrDefault(t => itemType.IsAssignableFrom(t.GetType()));
}
+5

, , :

// doesn't work
t is itemType

//working
t is String

So, as @AmirPopovich suggested, you can use a generic method that helps you provide you with a type is:

public static InventorySlot FindItem<T>(this IInventory inventory)
{
    return inventory.InventorySlots.FirstOrDefault(t => t is T);
}
+2
source

Source: https://habr.com/ru/post/1570771/


All Articles