简体   繁体   中英

C# comparing types for equality, with those types as parameters

I need to compare types in C# flexibly, for the purpose of testing types hierarchical relationships. My first try is

public class ParentInfo<PT> {  // PT = parent type expected
    
    public static bool hasParent(LDBRootStructs item) {
        var parent = item.parent;
        var rightParent = parent is PT;  // << this is the type test I want

This is fine but it means instantiating the generic parameter PT to a known class at compile time. I need it as a variable so I tried this instead

public static class ParentInfo2 {  // PT = parent type expected
    
    public static bool hasParent2(LDBRootStructs item,
                                      Type PT) {
        var parent = item.parent;
        var rightParent = parent is PT; <<< error here

but it complained “ Cannot implicitly convert type 'System.Type' to 'LDB.LDBRootStructs' ” and additionally I can't pass in the requested type as a parameter.

I can work around this by adding a test to each of my classes (each class has myOwnType virtual func which returns an int that is fixed for each class, just compare these ints), but is there an easier way? I've been looking at GetType and related but it's unclear.

I need to do this to create an interpreted DSL so it has to be flexible. I've looked for previous answers to this (this is SO, they must exist.) but I don't know what to look for.

-- edit, realised just a way to get a unique id (string, int, whatever) from a class would likely suffice .

You're trying to compare an instance of a class to an instance of Type - that wont work (or at least won't do what you expect).

Compare the type of parent to the type PT

var rightParent = parent.GetType() == PT; 

This will only match exactly. For a hierarchy/inheritance chain of types you could also use

var rightParent = PT.IsAssignableFrom(parent.GetType()); 

The reflection-based equivalent to

bool IsOfType<T>(object o)
{
    return o is T;
}

uses Type.IsAssignableFrom

bool IsOfType(object o, Type t)
{
    return t.IsAssignableFrom(o.GetType());
}

This should work

        var foo = new Foo();
        Type bar = typeof(Foo);

        if (foo.GetType().Equals(bar))
        {

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM