2012-12-26 98 views
1

我写的这个课程是否足够(我是指专业人员这样做)被包含在代码/项目中?或者我错过了重要的事情?我不知道如何使用构造函数等,所以我没有使用相同的语言(我只是C#中的初学者),但如果需要,请发表评论。课堂设计质量

using System; 
using System.Collections.Generic; 
using System.Text; 

namespace RandBit 
{ 
    /// <summary> 
    /// By: Author 
    /// Version 0.0.1 
    /// Pseudo-Random 16-Bit (Max) Generator. 
    /// </summary> 
    public class RandomBit 
    { 
     /// <param name="input">The Bit-size(int)</param> 
     /// <returns>Random Bit of Bit-size(string)</returns> 
     public static string Generate(int input) 
     { 
      int bitSize = 0; 
      Random choice = new Random(); 
      if (input == 0 || input > 16) 
      { 
       bitSize = 0; 
      } 
      else if (input == 1) 
      { 
       bitSize = 1; 
      } 
      else 
      { 
       int randomChoice = choice.Next(0, (1 << input)); 
       bitSize = randomChoice; 
      } 
      string binary = Convert.ToString(bitSize, 2); 
      binary = binary.PadLeft(input, '0'); 
      return binary; 
     } 
    } 
} 

谢谢。

回答

2

看起来您错误地使用了Random。我建议从Jon Skeet's article on the subject开始。相关报价:

如果用相同的初始状态 (可通过种子来提供)开始随机的一个实例,使 方法相同的序列调用它,你会得到同样的结果。

那么在我们的示例代码中出了什么问题?我们在循环的每次迭代中都使用了一个新的实例 Random。 Random的无参数构造函数 将当前日期和时间作为种子 - 在内部计时器 计算出当前日期和时间已更改之前,您通常可以执行相当数量的代码。因此,我们是 重复使用相同的种子 - 并重复获得相同的结果 。

换句话说,因为你正在创建的Random一个新实例每次调用,你是大大增加了机会,返回值将不会像“随机”如你所愿。

另外值得一提的是,在.Net BCL中已经有potentially better PRNG类。这是编写类似代码的另一种方式。

private static readonly RNGCryptoServiceProvider _crypto = new RNGCryptoServiceProvider(); 

public static long Generate(){ 
    // use whatever size you want here; bigger has a better chance of 
    // being unique in a given scope 
    byte[] bytes = new byte[8]; 

    // puts random bytes into the array 
    _crypto.GetBytes(bytes); 

    // do something (your choice) with the value... 
    return BitConverter.ToInt64(bytes, 0); 
} 
+0

感谢您的意见。我如何解决这个问题? –

+1

最重要的一点是保留一个RNG实例,而不是重复创建新的实例。我添加了一个示例,显示了这样做的一种方式,并且还使用了更强大的RNG。我链接的文章显示了使用“随机”和“RNGCryptoServiceProvider”的各种方法。 –

2

你可能只能改变一件事,因为你的类只包含一个静态成员,为什么不把该类设为静态。

1

如果我是项目组组长,我会要求您删除摘要/作者/版本注释。它们是多余的(源代码管理有这样的信息),需要一些时间来编写/修改,并且是不明确的(在7位作者的修改文件中)。

这里有一个关于这个话题的讨论,也许不是唯一的一个:https://softwareengineering.stackexchange.com/q/48562/30927

+0

确实不错! –

0

移动变量“选择”接近其他环路内的使用即。 否则,即使未使用,您也会为随机对象分配不必要的内存。 请参阅here