繁体   English   中英

我可以创建一种接口类型的通用方法吗?

[英]Can I Create A Generic Method of a Type of Interface?

是否可以创建带有签名的通用方法

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

我必须使用(T)Activator.CreateInstance();创建接口吗(T)Activator.CreateInstance();

如果要创建实现接口的某种类型的新实例并传递一些数据,则可以执行以下操作:

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

并这样称呼它:

string s = MyMethod<ClassImplementingIMyTypeOfInterface>(data);

您不能实例化接口。 您只能实例化实现该接口的类。

您可以将type参数约束为实现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
}

但是,您将永远无法“实例化接口”。

您不能实例化一个接口,但是可以确保通过泛型参数传递的类型实现该接口:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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