c# - How to compare object's type with a generics type, irrelevant to generic argument? -
The best way to illustrate my question is the example code:
class items {} Square container & lt; T & gt; {} Class program {static zero} some object (commodity object) {if (type of (object) == some. Gatetype ()) {System.Console.WriteLine ("item"); } And if (typef (container <) == some. Gatetype ()) {System.Console.WriteLine ("container <";); }} Fixed Zero main (string [] Args) {Haveings (new item ()); DoSomething (new container & lt; int & gt; ()); }}
The following line will not work:
else if (containof >) == something.GetType ())
Is this explicitly the container & lt; & Gt; In
the container & lt; Int & gt; Is there a way to work without changing
? I want to know that the object is of type 'container' and I am not really interested in container & lt; Int & gt;
or container & lt; String & gt;
Any sign except dozens of line reflections? Try
:
(container & lt; Gt;) == Some GetType (). GetGenericTypeDefinition ()
Note that this will only be true if the original type container
false
for the following:
class string container: container & lt; String & gt;
If you need to work for this matter, then you should cross the succession hierarchy and container & lt; T & gt; To be
:
Fixed bool isGenericTypeOf (type generic type, type some type) {If (some type IGenericType & amp; GenericType == someType.GetGenericTypeDefinition ()) return true; Type something. Type the base! = Null & amp; Amp; IsGenericTypeOf (Normally, someType.BaseType); }
Comments
Post a Comment