简体   繁体   中英

Get implementer class instance from the interface instance

I have some classes implementing an interface:

class FirstImplementer : IInterface { ... }
class AnotherImplementer : IInterface { ... }

Somewhere in the code, I got a list of instances of IInterface.

List<IInterface> MyList;

I want to know for each IInterface instance what is the implementer class of that specific instance (FirstImplementer or AnotherImplementer).

You can just use .GetType() on the instances in MyList and go from there.

MyList[0].GetType() > This is the same as typeof(FirstImplementer) et al.

foreach (var item in MyList)
{
    var theType = item.GetType();
    // why did you want theType, again?
    // you generally shouldn't be concerned with how your interface is implemented
}

This alternative may be more useful, depending on what you're trying to do:

foreach (var item in MyList)
{
    if (item is FirstImplementer)
    {
        var firstImpl = (FirstImplementer)item;
        // do something with firstImpl
    }
    else if (item is AnotherImplementer)
    {
        var anotherImpl = (AnotherImplementer)item;
        // do something with anotherImpl
    }
}

It's generally better to use is or as over reflection (eg GetType ) when it might make sense to do so.

foreach (var instance in MyList)
{
    Type implementation = instance.GetType ();
}

If you need to get the first type argument if any, and null if no such type argument even exists for each instance in your list, which at design time you syntactically observe as interface references then you could use the GetGenericArguments method of the Type type.

Here's a little helper method which takes a bunch of objects which may be null, but which would surely implement your interface if they weren't (they would have a runtime type that did) and yields a bunch of types which represent (in respective order) the discovered type arguments in a SomeImplementer pattern:

public IEnumerable<Type> GetTypeArgumentsFrom(IEnumerable<IInterface> objects) {
    foreach (var obj in objects) {
        if (null == obj) {
            yield return null; // just a convention 
                               // you return null if the object was null
            continue;
        }

        var type = obj.GetType();
        if (!type.IsGenericType) {
            yield return null;
            continue;
        }

        yield return type.GetGenericArguments()[0];
    }
}

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