Oleksandr Kryvenko
Oleksandr Kryvenko

Reputation: 1

C# Link interface class with a generic

I have 3 class and I need to tie them with a generic. I tried this way, but this don't help. Because I do not have access to the fields of the Sp.

Ch

 using System;
 using UnityEngine;

 public abstract class Ch<C, S> : MonoBehaviour
        where C : Ch<C, S>
        where S : Sp<S, C>
 {

     public void Connect()
     {
         S.iii = 10;
     }

 }

Sp

using UnityEngine;

public abstract class Sp<S, C> : Singleton<Sp<S, C>>
    where S : Sp<S, C>
    where C : Ch<C, S>
{

    public static int iii = 0;

}

UPD. If I convert the code to the following form. I get an errors "The type Ch cannot be used as type parameter C in the generic type Up. There is no implict reference conversation from Ch to Ch>>"

using UnityEngine;

public abstract class Sp<C> : Singleton<Sp<C>>
    where C : Ch<Sp<C>>
{

    public static int i = 0;


}


using System;
using UnityEngine;

public abstract class Ch<S> : MonoBehaviour
    where S : Sp<Ch<S>>
{

    public void Connect()
    {
        S.iii = 10;
    }

}

Upvotes: 0

Views: 74

Answers (1)

Enigmativity
Enigmativity

Reputation: 117037

The error would have been:

'S' is a type parameter, which is not valid in the given context

You can't do S.iii = 10;, it must be Sp<S, C>.iii = 10;.

This compiles:

public abstract class Ch<C, S>
    where C : Ch<C, S>
    where S : Sp<S, C>
{
    public void Connect()
    {
        Sp<S, C>.iii = 10;
    }
}

public abstract class Sp<S, C> : Singleton<Sp<S, C>>
    where S : Sp<S, C>
    where C : Ch<C, S>
{
    public static int iii = 0;
}

Upvotes: 2

Related Questions