[英]Use a random in a static class
我在項目中創建了一個類,以創建可以從其他表單執行的“全局方法”。 我不確定這是否不好,但是因為它是一個static class
,所以我不能(輕松地)在其中使用Random
。 我的代碼沒有聲明隨機性如下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DefaultNamespace;
namespace LevelGenerator
{
public static class LevelGen
{
static int levelIndex = 0;
static DefaultNamespace.frmSplashScreen myMenu = new DefaultNamespace.frmSplashScreen();
public static void NewLevel()
{
levelIndex = rnd.Next(1, 6);
簡而言之,我需要一個可以在任何地方調用的方法-這就是為什么我使用static class
-但它也需要具有Random
。 我想有很多方法可以做到這一點。
您可以添加靜態構造函數來初始化類(靜態)變量。 或為此,您可以簡單地使用組合的初始化和聲明語句。
所以要么顯式:
namespace LevelGenerator {
public static class LevelGen {
static Random random;
static LevelGen() {
random = new Random();
}
// ...
}
}
或隱式:
namespace LevelGenerator {
public static class LevelGen {
static Random random = new Random();
// ...
}
}
創建myMenu變量的方式相同
static DefaultNameSpace.frmSplashScreen myMenu = new DefaultNameSpace.frmSplashScreen();
您也可以創建rnd變量
static Random rnd = new Random();
由於System.Random
是一個類,因此您可以具有Random
類型的字段或屬性
public static Random Rng;
從那里,您可以從靜態構造函數內聯初始化,也可以要求調用初始化函數。 如果您希望從用戶那里收集種子值,我會建議最后一個,因此我將在下面演示
private static bool _randomReady = false;
public static Random Rng;
public static void SeedRandom(int seed)
{
// By not checking random ready here you will be able to reset the random later
Rng = new Random(seed);
_randomReady = true;
}
public static void NewLevel()
{
// By checking random ready, you can throw a more useful exception than NullReferenceException
if(!_randomReady)
throw new InvalidOperationException("Random Number Generation is not ready - call SeedRandom first!");
levelIndex = Rng.Next(1, 6);
使用實例管理,例如:
public class MyRandom
{
static Random random;
public static Random Random
{
get
{
if (random == null)
random = new Random(DateTime.Now.Milliseconds)
return random;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.