小编Run*_*org的帖子

C#通用接口专业化

我想知道在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
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让它在通过界面调用时使用专门版的Store?如果没有,有没有人知道C#以这种方式处理通用参数的确切原因?

编辑:如果C#无法在多个步骤中解析模板参数,则可以解决该问题.

void Foo<T>(T t)
{
    SubFoo(t);
}

void SubFoo<T>(T t)
{
    Console.WriteLine("Generic");
} …
Run Code Online (Sandbox Code Playgroud)

c#

15
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×1