How can I check if a class instance is a specific generic type?

Let's say I have a simple general class as follows

public class MyGenericClass<t>
{
   public T {get;set;}
}

How can I check if a class instance is this MyGenericClass? For example, I want to do something like this:

MyGenericClass x = new MyGenericClass<string>();
bool a = x is MyGenericClass;
bool b = x.GetType() == typeof(MyGenericClass);

But I can’t just indicate MyGenericClass. Visual Studio always wants me to write MyGenericClass<something>.

+3
source share
3 answers

To check if your instance is a type MyGenericClass<T>, you can write something like this.

MyGenericClass<string> myClass = new MyGenericClass<string>();
bool b = myClass.GetType().GetGenericTypeDefinition() == typeof(MyGenericClass<>);

, MyGenericClass MyGenericClass<string>, MyGenericClass. / , . . *

* , ,

var myClass = new MyGenericClass<string>();

: , class Foo : MyGenericClass<string>. Foo MyGenericClass<>, .

Func<object, bool> isMyGenericClassInstance = obj =>
    {
        if (obj == null)
            return false; // otherwise will get NullReferenceException

        Type t = obj.GetType().BaseType;
        if (t != null)
        {
            if (t.IsGenericType)
                return t.GetGenericTypeDefinition() == typeof(MyGenericClass<>);
        }

        return false;
    };

bool willBeTrue = isMyGenericClassInstance(new Foo());
bool willBeFalse = isMyGenericClassInstance("foo");
+2
List<int> testInt = new List<int>();
List<string> testString = new List<string>();

if (testInt .GetType().Equals(testString.GetType()))
 Console.WriteLine("Y");
else Console.WriteLine("N");

'N'

testInt.GetType().Equals(typeof(List<int>))
is true

u

testInt.GetType().FullName
0

, , (, ) . , - , , . .

0
source

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


All Articles