You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity植物养护游戏开发:泛型Gene<T>类使用报错求助

解决Unity中泛型Gene类无法作为非泛型类型使用的问题

问题原因

你创建的Gene<T>是泛型抽象类,C#中泛型类必须明确指定类型参数(比如Gene<float>、Gene<int>)才能作为类型声明使用。直接写Gene[]或者Gene作为返回类型时,编译器无法确定具体的泛型参数,因此会报错the generic type 'Gene<T>' requires 1 type arguments。

至于foreach那行暂时没报错,是编译器的语法提示延迟,实际编译时同样会失败。

解决方案:引入非泛型基类/接口

要让不同类型的Gene能被统一存储和处理,需要创建一个非泛型的基类或接口,让所有泛型Gene<T>继承它。这样就可以用这个非泛型基类来声明数组、方法返回类型。

步骤1:创建非泛型基类

先定义一个包含所有基因公共非泛型成员的抽象类(比如你代码里用到的GetName()方法):

public abstract class GeneBase
{
    // 所有基因都需要实现的非泛型方法/属性
    public abstract string GetName();
}

步骤2:修改泛型Gene继承非泛型基类

让Gene<T>继承上面的GeneBase,保留原有的泛型属性:

public abstract class Gene<T> : GeneBase
{
    public abstract T value { get; set; }
    public abstract T randomRange { get; set; }
}

步骤3:修正Genome结构体

把原来的Gene替换成GeneBase,同时修正代码里的拼写错误和返回值问题:

public struct Genome
{
    public GeneBase[] genes; // 用非泛型基类声明数组
    
    public GeneBase GetGeneByName(string name) // 修正拼写:Ny → By
    {
        foreach(GeneBase gene in this.genes)
        {
            if (gene.GetName() == name) return gene;
        }

        Debug.LogError($"It seems that the gene '{name}' couldn't be found in the genome. Maybe it does not exist or the spelling is wrong.");
        return null; // 必须返回值,否则编译报错
    }
}

步骤4:派生类补充实现基类方法

你的GeneFloat等派生类需要补充实现GeneBase的GetName方法,其他逻辑保持不变:

public class GeneFloat : Gene<float>
{
    public override string GetName() => "GrowthRate"; // 根据实际基因名称返回
    public override float value { get; set; }
    public override float randomRange { get; set; }
}

后续使用:获取具体类型的基因

当你从Genome中获取到GeneBase对象后,可以通过类型转换得到具体的泛型基因:

var genome = new Genome();
// 假设已经给genes数组添加了GeneFloat实例
var growthGene = genome.GetGeneByName("GrowthRate") as GeneFloat;

if (growthGene != null)
{
    // 使用具体类型的属性
    float currentGrowth = growthGene.value;
    growthGene.value += 0.1f;
}

内容的提问来源于stack exchange,提问作者Arthur Détaille

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 04:09:56