开发者

How can I compare two System.Types?

I have done this a gazillion times before but my memory fails me and I feel somewhat stupid asking this.

How do I compare two runtime types? I assume System.Type does not override the == operator and therefore the operator does a reference equality check.

I want to do a value equality. Like:

someObject.GetType() == GetTypeFromSomeAssemblyUsingReflection(
                                                "Namespace.TypeName",
                                                objAssemblyToGetTheTypeFrom);

I co开发者_如何学运维uld use IsAssignableFrom() but that would not be accurately what I am trying to do as it would broaden the scope. I want to just equate the types just as I'd do with:

if obj is Cat // where Cat is the name of a class

or

if ( (obj as Cat) != null )


The == operator should do the trick for type equality checks. For example, this passes:

[Test]
public void TypeEquality()
{
    var monkey = new Monkey();
    var areEqual = (monkey.GetType() == typeof(Monkey));
    Assert.That(areEqual, Is.True);
}


Type does override the equality operator, as seen in the documentation.


If you want obj is Cat behavior, IsAssignableFrom does actually work:

obj is Cat

is equivalent to:

typeof(Cat).IsAssignableFrom(obj.GetType())

For instance:

object siamese = new SiameseCat();

bool a = siamese is Cat;

// this is functionaly equivalent.
bool b = typeof(Cat).IsAssignableFrom(siamese.GetType());


if ( obj1.GetType().FullName == obj2.GetType().FullName )

if you need to create the object from an assembly dynamically, use such a method:

public object createObjectFromAsm( string asm, string type )
{
    // get the domain
    AppDomain ad = AppDomain.CurrentDomain;
    // create the object handle from the assembly
    System.Runtime.Remoting.ObjectHandle sVal = ad.CreateInstanceFrom( asm, type );
    // unwrap the object
    return sVal.Unwrap();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜