How to use 'is' when a type is passed through a method?

I am trying to pass a type to a method where I can check if it is "specific". However, the code that I have below does not compile, and I wonder what happened. Compilation error: type or namespace name 'dataType' could not be found.

public static List<object> findType(Type dataType) { List<object> items = new List<object>(); foreach (KeyValuePair<int, object> entry in DataSource.ItemPairs) { if (entry.Value != null && entry.Value is dataType) { items.Add(entry.Value); } } return items; } 
+6
source share
6 answers
Operator

is expects a type name, not an instance of Type . Therefore, the type must be known at compile time.

However, you can use the IsAssignableFrom method to check type compatibility:

 if (entry.Value != null && dataType.IsAssignableFrom(entry.Value.GetType()) 
+9
source

is is a special compiled construct in C # - you cannot put a variable as a type, you must write the actual type name.

If you want to check the exact type, use this:

 if(entry.Value.GetType() == dataType) 

If you want to check if it is inherited, you can use this:

 if (entry.Value != null && dataType.IsAssignableFrom(entry.Value.GetType())) 
+5
source

I think you want to check the entry.Value type.

Try the following:

 if (entry.Value != null && dataType.GetType().IsAssignableFrom(entry.Value)) 

He expects dataType be a property in itself, and this is a variable of type Type .

+2
source

If you can use generics and LINQ, things get a lot easier. Assuming DataSource.ItemPairs is a dictionary type.

 public static List<T> findType<T>() { List<T> items = new List<T>(); foreach (T entry in DataSource.ItemPairs.Values.OfType<T>()) { items.Add(entry); } return items; } 

Or even shorter than that.

 public static List<T> findType<T>() { return DataSource.ItemPairs.Values.OfType<T>().ToList(); } 
+2
source

entry.Value - an object, each object received a GetType () method, which returns a Type object to you. Type.Equal can compare these types. You can do this without using the word "is".

You cannot use the word is because "is" want to restore an object, not a type

0
source

Like other answers showing how to use an instance of Type , you can make your method generic. This will allow you to use is , but it clearly depends on the type of target fixed at compile time:

 public static List<object> findType<TTarget>() { List<object> items = new List<object>(); foreach (KeyValuePair<int, object> entry in DataSource.ItemPairs) { if (entry.Value != null && entry.Value is TTarget) { … 
0
source

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


All Articles