【发布时间】:2020-08-10 10:27:16
【问题描述】:
我想知道是否可以在 C# 中以某种方式专门化泛型接口方法?我发现了类似的问题,但没有完全像这样的问题。现在我怀疑答案是“不,你不能”,但我想确认一下。
我所拥有的类似于以下内容。
public interface IStorage
{
void Store<T>(T data);
}
public class Storage : IStorage
{
public void Store<T>(T data)
{
Console.WriteLine("Generic");
}
public void Store(int data)
{
Console.WriteLine("Specific");
}
}
class Program
{
static void Main(string[] args)
{
IStorage i = new Storage();
i.Store("somestring"); // Prints Generic
i.Store(1); // Prints Generic
Storage s = (Storage)i;
s.Store("somestring"); // Prints Generic
s.Store(1); // Prints Specific
}
}
有没有办法让它在通过接口调用时使用专门版本的Store?如果没有,有谁知道 C# 以这种方式处理泛型参数的确切原因吗?
编辑: 如果不是 C# 无法在多个步骤中解析模板参数,则可以解决此问题。
void Foo<T>(T t)
{
SubFoo(t);
}
void SubFoo<T>(T t)
{
Console.WriteLine("Generic");
}
void SubFoo(int t)
{
Console.WriteLine("Specific");
}
这里对 Foo(1) 的调用也会打印“Generic”,编译器不应该能够解决这个问题吗?或者 JIT 会阻止这种情况发生吗?
【问题讨论】:
标签: c#