Make an interface method return an object of the class type that implemented it

I was looking for an answer to accomplish this, but I didn't find anything: I want the interface method to return an object of the class type that implemented it. For instance:

interface InterfaceA {
   public static returnValue getObjectFromDatabase(); //What do i need to put as returnValue?
}

Then, if I have two classes (e.g. ClassA and ClassB) that implement it, I would like to have:

ClassA obj1 = ClassA.getObjectFromDatabase(); //return object of class ClassA
ClassB obj2 = ClassB.getObjectFromDatabase(); //return object of class ClassB

Thanks in advance.

+4
source share
3 answers

What you want to do here will not work for two reasons:

  • Interfaces cannot have static elements
  • . , , .

, , , . , , , , , , .

, , , , Employee. , , Employee . , FirstName, GivePromotion() .. , .

, , , . - . , , . , :

public interface IRepository<T>
{
    T GetFromDatabase()
}

:

public class Repository<T> : IRepository<T>
{
    T GetFromDatabase()
    {
        //Your actual code for database retrieval goes here
    }
}

, , :

public class EmployeeRepository : IRepository<Employee>
{
    Employee GetFromDatabase()
    {
        //Your actual code for database retrieval goes here
    }
}
+10

:

class Program
{
    interface MyInterface<SomeType>
    {
        SomeType getObjectFromDatabase ();
    }

    class A : MyInterface<A> { public A getObjectFromDatabase () { return new A (); } }
    class B : MyInterface<B> { public B getObjectFromDatabase () { return new B (); } }

    class Program2
    {
        static void Main ()
        {
            A a1, a2;
            a1 = new A ();
            a2 = a1.getObjectFromDatabase ();
            B b1, b2;
            b1 = new B ();
            b2 = b1.getObjectFromDatabase ();
        }
    }
}
+2

, , >

, : . .

, , static, . , .

+1

Source: https://habr.com/ru/post/1536240/


All Articles