C# generic interface specialization

前端 未结 6 1743
自闭症患者
自闭症患者 2020-12-10 02:42

I wonder if it is in any way possible to specialize generic interface methods somehow in C#? I have found similar questions, but nothing exactly like this. Now I suspect tha

6条回答
  •  萌比男神i
    2020-12-10 03:27

    If you want to take advantage of compile-time overload resolution you may as well extend the interface with a method that takes an int:

    public interface IStorage
    {
        void Store(T data);
    }
    
    public interface IIntStorage: IStorage
    {
        void Store(int data);
    }
    
    public class Storage : IIntStorage
    {
        public void Store(T data)
        {
            Console.WriteLine("Generic");
        }
    
        public void Store(int data)
        {
            Console.WriteLine("Specific");
        }
    }
    

    Now if you call Store(1) through the IIntStorage interface it will use the specialized method (similar to how you called Storage's method directly), but if you call it through IStorage it will still use the generic version.

提交回复
热议问题