简体   繁体   English

具有泛型的C#Link接口类

[英]C# Link interface class with a generic

I have 3 class and I need to tie them with a generic. 我有3个班级,我需要将它们与通用类联系起来。 I tried this way, but this don't help. 我尝试过这种方式,但这无济于事。 Because I do not have access to the fields of the Sp. 因为我无法访问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 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. 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>>" 我收到一个错误“类型Ch不能用作通用类型Up中的类型参数C。从Ch到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;
    }

}

The error would have been: 该错误将是:

'S' is a type parameter, which is not valid in the given context 'S'是类型参数,在给定的上下文中无效

You can't do S.iii = 10; 你不能做S.iii = 10; , it must be Sp<S, C>.iii = 10; ,必须为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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM