Pass in Type to check against
I have a method in which I'm doing a check to see if the current object in a loop is the same type as a type I pass into the method.
At first I was passing the type into the method as a string and then using:
item.GetType().ToString().Equals(myType);
What I'd really prefer to do is use the is
keyword to do:
item is myType
The problem I'm having is passing in myType
to the method. Do I need to use some kind of funky generics type or somethin开发者_如何学Pythong? What type do I pass in a reference ot a type as?
Is it something like this?
public static bool ContainsType<T>()
{
object[] objects = new object[] { };
foreach (var o in objects)
{
if (o is T)
{
return true;
}
}
return false;
}
public static void Main(string[] args)
{
ContainsType<int>();
}
Do you mean something like:
public List<T> GetItemsOfType<T>(List<object> allObjects)
{
return allObjects.Where(o => o is T).Cast<T>().ToList();
}
Which you would then call with something like
var result = GetItemsOfType<MyType>(myObjects);
You can use the normal equality operator:
item.GetType() == myType;
This will return true
if item is of the exact type that myType describes. Note that it will return false
if there is any difference, though:
class A { }
class B : A { }
B item = new B();
Type myType = typeof(A);
bool sameType = item.GetType() == myType; // this will be false
One good thing to know about Type
objects is this text that is to be found in the documentation:
A
Type
object that represents a type is unique; that is, twoType
object references refer to the same object if and only if they represent the same type. This allows for comparison ofType
objects using reference equality.
精彩评论