C# generic interface specialization

前端 未结 6 1757
自闭症患者
自闭症患者 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 03:15

    You can do it by introducing additional type information (e.g. implementing an interface). Here is an example.

    // no need to modify the original interface
    public interface IStorage
    {
        void Store(T data);
    }
    

    Implementation with specialization based on a generic interface

    public class Storage : IStorage,
        Storage.ISpecializedFor,
        Storage.ISpecializedFor
    {
        // a private interface to provide additional type info
        private interface ISpecializedFor
        {
            void Store(T data);
        }
    
        public void Store(T data)
        {
            // resolve specialization
            if (this is ISpecializedFor specialized)
            {
                specialized.Store(data);
            }
            else
            {
                // unspecialized implementation goes here
                Console.WriteLine("Unspecialized");
            }
        }
    
        // specialized implementation
        void ISpecializedFor.Store(int data)
        {
            Console.WriteLine("Specialized for int");
        }
    
        void ISpecializedFor.Store(double data)
        {
            Console.WriteLine("Specialized for double");
        }
    }
    

    Results

    void Main()
    {
        IStorage storage = new Storage();
    
        storage.Store("hello"); // prints "Unspecialized"
        storage.Store(42); // prints "Specialized for int"
        storage.Store(1.0); // prints "Specialized for double"
    }
    

提交回复
热议问题