Dan*_*tin 1 c# generics interface
我有一个方法,我想重新创建更通用的方法。
public Task<bool> DoSomething<T>(T t) where T : Type, IAnyInterface
Run Code Online (Sandbox Code Playgroud)
如您所见,我想要一个Type作为参数,它必须实现IAnyInterface
但如果我调用该方法,
DoSomething(typeof(ObjectThatImplementsIAnyInterface));
Run Code Online (Sandbox Code Playgroud)
我收到错误:
类型“System.Type”不能用作泛型类型或方法“DoSomething(...)”中的类型参数“T” 没有从“System.Type”到“IAnyInterface”的隐式转换
那么我怎样才能让该方法接受该类型呢?
不想传输实例,否则我想在方法 DoSomething(...) 中创建实例
然后只需省略该参数即可。在你的情况下它似乎没有用。让规范在通用调用中完成:
public Task<bool> DoSomething<T>() where T : IAnyInterface
{
Type type = typeof(T);
// Or create the entire instance:
T newInstance = Activator.CreateInstance<T>();
}
Run Code Online (Sandbox Code Playgroud)
称呼:
DoSomething<ObjectThatImplementsIAnyInterface>();
Run Code Online (Sandbox Code Playgroud)
编辑:创建实例的另一种方法是要求无参数构造函数:
public Task<bool> DoSomething<T>() where T : IAnyInterface, new()
{
T newInstance = new T();
}
Run Code Online (Sandbox Code Playgroud)