How to create groups of related types for use in C # generics if there is no `typedef`?

As someone who comes from C ++ background, I came across the following situation:

Given that C # does not support typedefs, how do you programmatically bind types. That is, in C ++, I can store related types as typedefs for retrieval when used with templates. The same cannot be done in C # in the same way due to a lack typedef.

For example, in C ++ I would:

template< typename T >
class Thing : public ThingBase<T>
{
   public:
       bool isRelated( T::Parent & otherThing )
       {
           T::Auxillary aux( "Yes" );            
           return aux.isValid( otherThing ) && data.isParent( otherThing );
       }
   private:
       T data;
};

This will work with any of the following methods:

class SomeClass
{
    public:
        typedef SomeClassParent Parent; 
        typedef FooAuxillary    Auxillary;

        bool isParent( Parent & parentObject );
};

class OtherClass
{
    public:
        typedef OtherClassParent Parent; 
        typedef BarAuxillary     Auxillary;

        bool isParent( Parent & parentObject );
};

Although the ability to call T::isParentby parameter type can be achieved using a common interface interface, creating a signature for Thing::isRelatedit seems impossible without typedefs.

So, in C #, what should I do to get the associated interface type for T (which is T :: Interface in the C ++ example)?

+2
2

(, , ), SLaks, .

interface IRelated<TRelated>
{
    bool isParent(TRelated parentObject);
}

class SomeClassParent {}
class SomeClass : IRelated<SomeClassParent>
{
    bool isParent(SomeClassParent parentObject)
    {
        // your logic here
        return true;
    }
}

class Thing<T, TParent> : ThingBase<T> where T : IRelated<TParent> {}

:

var obj = new Thing<SomeClass, SomeClassParent>();

. ( isParent ), .

interface IRelated
{
    bool isParent<T>(T parentObject);
}

class SomeClassParent {}
class SomeClass : IRelated
{
    bool isParent<T>(T parentObject)
    {
        if (parentObject is SomeClassParent)
        {
            // your logic here
            return true;
        }
    }
}

class Thing<T> : ThingBase<T> where T : IRelated {}

:

var obj = new Thing<SomeClass>();
+2

:

interface IRelatedTo<TRelated> 
class Thing<T, TRelated> where T : IRelatedTo<TRelated>
0

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


All Articles