Sup*_*JMN 2 .net c# generics interface
我有这个界面
interface IMyInterface
{
object Create(Type t);
}
Run Code Online (Sandbox Code Playgroud)
为方便起见,我还会包含一个包含调用方法的泛型重载,因此它变为:
interface IMyInterface
{
object Create(Type t);
T Create<T>();
}
Run Code Online (Sandbox Code Playgroud)
新方法将像这样实现
public object Create<T>()
{
return (T) Create(typeof(T));
}
Run Code Online (Sandbox Code Playgroud)
方法的问题:
IMyInteface我该如何解决这个设计问题?
Gro*_*kys 12
最好的解决方案是使用扩展方法:
public static MyInterfaceExtensions
{
public T Create<T>(this IMyInterface target)
{
return (T) target.Create(typeof(T));
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以像常规方法一样调用扩展方法.