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;
        }
    }
    
    
  • 相关阅读:
    Hibernate- 连接查询
    Hibernate- 条件查询
    Hibernate- 分页查询
    Hibernate- 动态实例查询
    java- 控制double输出的小数点位数
    Hibernate- 基本查询
    Hibernate- 开发环境准备
    Hibernate- HQL查询方式
    Hibernate-【查询】
    Hibernate- 多对多
  • 原文地址:https://www.cnblogs.com/kingBook/p/15343030.html
Copyright © 2011-2022 走看看