gpt4 book ai didi

c# - 类设计质量

转载 作者:太空宇宙 更新时间:2023-11-03 20:20:14 24 4
gpt4 key购买 nike

我编写的这个类是否足以包含在代码/项目中(我指的是专业人士的做法)?还是我错过了重要的事情?我不知道如何使用构造函数等,所以我没有使用它们(我只是 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;
}
}
}

谢谢。

最佳答案

您似乎错误地使用了 Random。我建议从 Jon Skeet's article on the subject 开始.相关引用:

If you start off an instance of Random with the same initial state (which can be provided via a seed) and make the same sequence of method calls on it, you'll get the same results.

So what was wrong in our example code? We were using a new instance of Random on each iteration of the loop. The parameterless constructor for Random takes the current date and time as the seed - and you can generally execute a fair amount of code before the internal timer works out that the current date and time has changed. Therefore we're using the same seed repeatedly - and getting the same results repeatedly.

换句话说,由于您在每次调用时都创建了一个新的 Random 实例,因此您大大增加了返回值不像您期望的那样“随机”的可能性。

还值得一提的是,还有potentially better .Net BCL 中已有 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 );
}

关于c# - 类设计质量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14037448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com