简体   繁体   中英

Can I Create A Generic Method of a Type of Interface?

Is it possible to create a generic method with a signature like

public static string MyMethod<IMyTypeOfInterface>(object dataToPassToInterface)
{
    // an instance of IMyTypeOfInterface knows how to handle 
    // the data that is passed in
}

Would I have to create the Interface with (T)Activator.CreateInstance(); ?

If you want to create a new instance of some type implementing the interface and pass some data you could do something like this:

public static string MyMethod<T>(object dataToPassToInterface) where T : IMyTypeOfInterface, new()
{
    T instance = new T();
    return instance.HandleData(dataToPassToInterface);
}

and call it like this:

string s = MyMethod<ClassImplementingIMyTypeOfInterface>(data);

You can't instantiate interfaces. You can only instantiate classes that implement the interface.

You can constraint the type parameter to being something that implements IMyTypeOfInterface :

public static string MyMethod<T>(object dataToPassToInterface)
    where T : IMyTypeOfInterface
{
    // an instance of IMyTypeOfInterface knows how to handle 
    // the data that is passed in
}

However, you will never be able to "instantiate the interface".

You can't instantiate an interface, but you can ensure that the type passed as the generic parameter implements the interface:

    public static string MyMethod<T>(object dataToPassToInterface)
        where T : IMyTypeOfInterface
    {
        // an instance of IMyTypeOfInterface knows how to handle  
        // the data that is passed in 
    }

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