jeudi 2 août 2018

Cast to generic interface with where clause

I have an object that I want to call certain methods if it implements specific kinds of interfaces.

I am checking for the generic interfaces like below.

foreach (var iFace in objectType.GetInterfaces())
{
    if (iFace.IsGenericType && iFace.GetGenericTypeDefinition() == typeof(INotify<>))
    {
        //fails to compile because object isn't the correct type.
        doSomethingWithINotifyObject(object)
    }
    //do other things if different interfaces
}

What I don't know how to do is cast the object so that it is the correct type to call doSomethingWithINotifyObject

The method in this example looks something like this

private void doSomethingWithINotifyObject<T>(INotify<T> notify) where T : EventArgs, INotificationArgs
{
    //do stuff with notification object
}

The INotify interface is defined as

public interface INotify<T> where T: EventArgs, INotificationArgs
{
    //notify stuff
}

Is there any way to cast my object to an INotify<T> where T : EventArgs, INotificationArgs and not care what T actually is?





Aucun commentaire:

Enregistrer un commentaire