zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
    
  • 相关阅读:
    数据结构-串的堆分配存储
    ServerSocket
    Java-坦克大战
    Java-输入输出流
    MyEclipse 快捷键
    数据结构-串的定长顺序存储
    我的软考资料集合
    软考中级软件设计师考试大纲
    2016年第一季度阅读书目
    中国大陆开源镜像网站汇总
  • 原文地址:https://www.cnblogs.com/kingBook/p/15343030.html
Copyright © 2011-2022 走看看