C# 泛型约束为枚举


示例:根据权重对象列表随机返回一个枚举类型

using System.Collections;
using UnityEngine;

public static class WeightObjectsUtil {

    /// <summary>
    /// 随机在权重列表返回一个枚举类型
    /// </summary>
    /// <typeparam name="T"> 枚举类型 </typeparam>
    /// <param name="weightObjects"> 权重对象列表 </param>
    /// <param name="defaultType"> 默认返回的枚举类型 </param>
    /// <returns></returns>
    public static T GetLandTypeWithWeightList<T> ((T type, int weight)[] weightObjects, T defaultType) where T : System.Enum {
        // 总权重
        int sumWeight = 0;
        for (int i = 0, len = weightObjects.Length; i < len; i++) {
            sumWeight += weightObjects[i].weight;
        }

        // 随机数 [0, sumWeight)
        int n = Random.Range(0, sumWeight);
        // 根据随机数所在总权重线段上的落点计算出结果
        int m = 0;
        for (int i = 0, len = weightObjects.Length; i < len; i++) {
            (T landType, int weight) weightObj = weightObjects[i];
            if (n >= m && n < m + weightObj.weight) {
                return weightObj.landType;
            }

            m += weightObj.weight;
        }
        return defaultType;
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM