mardi 28 avril 2020

Calling a generic method using type variable [duplicate]

I am trying to call a generic method using classes that match an interface within the executing assembly and reflection. I'm stuck on how to pass the type as generic.

I end up with either one of two error messages:

a) By passing type directly: Type is a variable but is used like a type

or

b) By passing type.GetType(): Operator '<' cannot be applied to operands of type 'method group' and 'Type'

What I have so far:

public void LoadClasses()
{
    foreach (Type type in Assembly.GetExecutingAssembly().DefinedTypes)
        if (typeof(ISomeInterface).IsAssignableFrom(type))
            CallMethod<type>();
}

public void CallMethod<T>() where T : class, new()
{
    T instance = new T();
    ((ISomeInterface)instance).CallMethod();
}




Aucun commentaire:

Enregistrer un commentaire