static method cannot implement interface method, why?

后端 未结 6 1271
刺人心
刺人心 2021-02-20 04:24
interface IXXX
{
    void Foo();
}

class XXX : IXXX
{
    public static void Foo()
    {
        Console.WriteLine(\"From XXX\");
    }
}


class Program 
{
    static          


        
6条回答
  •  鱼传尺愫
    2021-02-20 04:34

    Well, I believe it should allowed in case of generic type parameter. It probably simplified contractual singleton class. Here is an example:

    public interface IEntity {
       // some constrains...
      DataRow ObjToRow(object obj);
      object RowToObj(DataRow dr);
    }
    
    //T would be any class inherites from IEntity with default contructor signature.
    public interface IMyContract {
      T read() where T : IEntity;  
      void write(T object) where T : IEntity;
    }
    
    //everything in the class is static
    public static class SqlProvider : IMyContract {
    
      public static T read() where T: IEntity {
        DataRow dr = [reading from database]
        return T.RowToObj(dr);
      }
    
      //compile error here....
      public static void write(T obj) where T : IEntity {
        DataRow dr = T.ObjToRow(obj);
    
       [ ... commit data row dr to database ... ]
    
      }
    }
    
    public static class MyAppleEntity : IEntity  {
      [... implement IEntity contract normally ... ]
    }
    
    public static class MyOrangeEntity : IEntity {
       [... implement IEntity contract normally ... ]
    }
    
    public class MyTest {
      void reading() {
         MyAppleEntity apple = SqlProvider.Read();
         MyOrangeEntity orange = SqlProvider.Read();
    
         SqlProvider.write(apple); 
         SqlProvider.write(orange);
      } 
    
    }
    

    The only time a type reference implicitly is in the SqlProvider.read() and write() and T is well identity at point of invoke. Without static implementation of interface I'm forced to write like this.

    public class MyAppleEntity : IEntity  {
      [... implement IEntity contract normally ... ]
    }
    
      .....
    
      public T read() where T: IEntity, new() {
        DataRow dr = [reading from database]
        return new T().RowToObj(dr);
      }
    

    Very little different but not quite as elegant.

提交回复
热议问题