C # constructor in interface

I know that you cannot have a constructor in an interface, but here is what I want to do:

 interface ISomething 
 {
       void FillWithDataRow(DataRow)
 }


 class FooClass<T> where T : ISomething , new()
 {
      void BarMethod(DataRow row)
      {
           T t = new T()
           t.FillWithDataRow(row);
      }
  }

I would really like to replace the method with a ISomething FillWithDataRowconstructor somehow.

That way, my member class can implement the interface and still be read-only (it cannot using the method FillWithDataRow).

Does anyone have a template that will do what I want?

+5
source share
2 answers

(At first I had to check, but I'm tired - this is basically a duplicate .)

factory, Func<DataRow, T> . ( . , , Injection Dependency, .)

:

interface ISomething 
{      
    // Normal stuff - I assume you still need the interface
}

class Something : ISomething
{
    internal Something(DataRow row)
    {
       // ...
    }         
}

class FooClass<T> where T : ISomething , new()
{
    private readonly Func<DataRow, T> factory;

    internal FooClass(Func<DataRow, T> factory)
    {
        this.factory = factory;
    }

     void BarMethod(DataRow row)
     {
          T t = factory(row);
     }
 }

 ...

 FooClass<Something> x = new FooClass<Something>(row => new Something(row));
+3

?

, ...

interface IFillable<T> {
    void FillWith(T);
}

abstract class FooClass : IFillable<DataRow> {
    public void FooClass(DataRow row){
        FillWith(row);
    }

    protected void FillWith(DataRow row);
}
+6

All Articles