What is the equivalent of inheriting C ++ templates in C #?

I understand that this is not possible in C #, because Generics are not templates, and they are implemented differently (processing at runtime, not at compile time):

public class Foo<T> : T
{

}

The question remains. Is there an equivalent, or perhaps an alternative way to achieve this?

In my case, I have three different parent classes that I want to inherit from, call them A, B, C:

public class A {}

public class B {}

public class C {}

Then I have a class Foo, and then MANY inherit from Foo, but each of them needs only one of A, B, C:

public class X : Foo<A> {} 

public class Y : Foo<B> {}

public class Z : Foo<C> {}

So the class X needs all the functions in Foo and all the functions in A, Y from Foo and B, etc ...

How to do it in C #?

+4
2

, A, B C ( Foo), : "Foo" ( "IFoo" ):

public interface IFoo {}

:

public static class IFooExtension
{
    public static void Method1(this IFoo f) {
        // do whatever here;
    } 
}

:

public class X : A, IFoo {}
public class Y : B, IFoo {}
public class Z : C, IFoo {}

( ) , , , .

0

class X: Foo<A> { } Foo A, A , :

public class Foo<T> where T : new()
{
    public T Bar { get; } = new T();
    public void FooMethod() => Console.WriteLine("Foo method");
}

public class A
{
    public void AMethod() => Console.WriteLine("A method");
}

public class X : Foo<A>
{
}

class Program
{
    static void Main(string[] args)
    {
        var x = new X();
        x.FooMethod();
        x.Bar.AMethod(); // access via property
    }
}
0

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


All Articles