首页 > 解决方案 > C# Link 接口类与泛型

问题描述

我有 3 节课,我需要将它们与泛型联系起来。我试过这种方式,但这没有帮助。因为我无法访问 Sp 的字段。

通道

 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。如果我将代码转换为以下形式。我收到错误“类型 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;
    }

}

标签: c#unity3dgenericsinterface

解决方案


错误是:

'S' 是一个类型参数,在给定的上下文中是无效的

你不能这样做S.iii = 10;,它必须是Sp<S, C>.iii = 10;

这编译:

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;
}

推荐阅读