欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺析C#如何隨機獲取枚舉中的變量

 更新時間:2025年07月23日 09:18:34   作者:張謹?shù)W  
在 C# 中,隨機獲取枚舉變量有多種實現(xiàn)方式,這篇文章主要為大家詳細介紹了四種常用的實現(xiàn)方法,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下

在 C# 中,隨機獲取枚舉變量有多種實現(xiàn)方式。下面為你介紹常用的方法,并給出示例代碼。

方法一:使用 Enum.GetValues 和 Random

這種方法先獲取枚舉的所有值,再用Random類隨機選擇一個。

using System;
?
public enum Color
{
    Red,
    Green,
    Blue,
    Yellow,
    Black
}
?
public static class EnumHelper
{
    private static Random random = new Random();
    
    public static T RandomEnumValue<T>() where T : Enum
    {
        Array values = Enum.GetValues(typeof(T));
        int index = random.Next(values.Length);
        return (T)values.GetValue(index);
    }
}
?
// 使用示例
Color randomColor = EnumHelper.RandomEnumValue<Color>();
Console.WriteLine(randomColor); // 輸出可能為:Blue

方法二:結(jié)合 LINQ 和 Random

借助 LINQ 的Cast方法,能讓代碼更簡潔。

using System;
using System.Linq;
?
public enum Direction
{
    North,
    South,
    East,
    West
}
?
public static class EnumRandomizer
{
    private static Random random = new Random();
    
    public static T RandomValue<T>() where T : Enum
    {
        Array values = Enum.GetValues(typeof(T));
        return (T)values.GetValue(random.Next(values.Length));
    }
    
    // 更簡潔的LINQ寫法
    public static T RandomValueLinq<T>() where T : Enum
    {
        return Enum.GetValues(typeof(T)).Cast<T>().ElementAt(random.Next(0, Enum.GetValues(typeof(T)).Length));
    }
}
?
// 使用示例
Direction randomDirection = EnumRandomizer.RandomValue<Direction>();
Console.WriteLine(randomDirection); // 輸出可能為:South

方法三:帶權(quán)重的隨機選擇

若你希望某些枚舉值被選中的概率更高,可使用帶權(quán)重的隨機選擇。

using System;
using System.Collections.Generic;
?
public enum Size
{
    Small,
    Medium,
    Large
}
?
public static class WeightedEnumRandomizer
{
    private static Random random = new Random();
    
    public static T RandomValue<T>(params (T value, int weight)[] weightedValues) where T : Enum
    {
        int totalWeight = 0;
        foreach (var (_, weight) in weightedValues)
        {
            totalWeight += weight;
        }
        
        int randomValue = random.Next(0, totalWeight);
        int currentWeight = 0;
        
        foreach (var (value, weight) in weightedValues)
        {
            currentWeight += weight;
            if (randomValue < currentWeight)
            {
                return value;
            }
        }
        
        throw new InvalidOperationException("No values provided.");
    }
}
?
// 使用示例 - Medium被選中的概率是Small和Large的2倍
Size randomSize = WeightedEnumRandomizer.RandomValue(
    (Size.Small, 1),
    (Size.Medium, 2),
    (Size.Large, 1)
);
Console.WriteLine(randomSize); // 輸出可能為:Medium

方法四:擴展方法實現(xiàn)

通過擴展方法,可以讓枚舉類型直接支持隨機選擇功能。

using System;
using System.Linq;
?
public enum Animal
{
    Dog,
    Cat,
    Bird,
    Fish
}
?
public static class EnumExtensions
{
    private static Random random = new Random();
    
    public static T Random<T>(this T @enum) where T : Enum
    {
        Array values = Enum.GetValues(typeof(T));
        return (T)values.GetValue(random.Next(values.Length));
    }
}
?
// 使用示例
Animal randomAnimal = default(Animal).Random();
// 或者
Animal anotherRandomAnimal = EnumExtensions.Random(Animal.Dog);
Console.WriteLine(randomAnimal); // 輸出可能為:Bird

性能考量

  • 對于小型枚舉,上述幾種方法的性能差異可以忽略不計。
  • 如果需要在循環(huán)中頻繁生成隨機枚舉值,建議復(fù)用Random實例,避免生成重復(fù)的隨機序列。
  • 帶權(quán)重的隨機選擇會增加一些計算開銷,但能實現(xiàn)更靈活的隨機行為。

根據(jù)你的具體需求,選擇合適的方法即可。如果需要更復(fù)雜的功能,比如排除某些枚舉值,可在上述代碼基礎(chǔ)上進行擴展。

到此這篇關(guān)于淺析C#如何隨機獲取枚舉中的變量的文章就介紹到這了,更多相關(guān)C#獲取變量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C#調(diào)用sql2000存儲過程方法小結(jié)

    C#調(diào)用sql2000存儲過程方法小結(jié)

    這篇文章主要介紹了C#調(diào)用sql2000存儲過程的方法,以實例形式分別對調(diào)用帶輸入?yún)?shù)及輸出參數(shù)的存儲過程進行了詳細分析,非常具有實用價值,需要的朋友可以參考下
    2014-10-10
  • C#如何解析http報文

    C#如何解析http報文

    這篇文章如果講解了用C#如何解析http報文,要解析http報文,需要哪些操作呢?下面小編給大家整理相關(guān)資料,需要的朋友可以參考下
    2015-08-08
  • 詳解WPF如何使用必應(yīng)地圖控件

    詳解WPF如何使用必應(yīng)地圖控件

    這篇文章主要為大家詳細介紹了WPF如何使用必應(yīng)地圖控件,文中的示例代碼講解詳細,對我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下
    2022-11-11
  • C#傳值方式實現(xiàn)不同程序窗體間通信實例

    C#傳值方式實現(xiàn)不同程序窗體間通信實例

    Form2構(gòu)造函數(shù)中接收一個string類型參數(shù),即Form1中選中行的文本,將Form2的TextBox控件的Text設(shè)置為該string,即完成了Form1向Form2的傳值
    2013-12-12
  • 深入理解C#中常見的委托

    深入理解C#中常見的委托

    這篇文章主要介紹了C# 委托(Delegate)的相關(guān)資料,文中講解非常詳細,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下,希望能夠幫助到你
    2021-07-07
  • gridview 顯示圖片的實例代碼

    gridview 顯示圖片的實例代碼

    gridview 圖片的二進制數(shù)據(jù)庫存儲和顯示
    2013-04-04
  • winform天氣預(yù)報小工具(附源碼下載)

    winform天氣預(yù)報小工具(附源碼下載)

    主要原理就是利用網(wǎng)上免費的webservice獲取天氣數(shù)據(jù),需要的朋友可以參考下
    2012-03-03
  • C#版的 Escape() 和 Unescape() 函數(shù)分享

    C#版的 Escape() 和 Unescape() 函數(shù)分享

    從網(wǎng)上看到兩個方法, C# 版的 Escape() 和 Unescape(),收藏下。
    2011-05-05
  • C# Winform截圖指定控件范圍內(nèi)的圖像的流程步驟

    C# Winform截圖指定控件范圍內(nèi)的圖像的流程步驟

    工作所需,需要截圖軟件跑出來的界面上的圖表,但是窗口本身是可以縮放的,圖表也是做的可以跟著窗體大小一起縮放,所以就寫了一個函數(shù),用于截圖圖表容器內(nèi)的圖像,文中有函數(shù)源碼供大家參考,需要的朋友可以參考下
    2024-10-10
  • WPF中ImageBrush常用方式介紹

    WPF中ImageBrush常用方式介紹

    這篇文章介紹了WPF中ImageBrush的常用方式,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06

最新評論