Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#在另一个字符串的字符之间插入一个随机字符串_C#_.net_Random_Replace_Colors - Fatal编程技术网

C#在另一个字符串的字符之间插入一个随机字符串

C#在另一个字符串的字符之间插入一个随机字符串,c#,.net,random,replace,colors,C#,.net,Random,Replace,Colors,我想创建一个方法,在字符串中的字符之间插入随机十六进制颜色。这就是我目前所拥有的 `public static string colorString(string input) { var random = new System.Random(); string hexcolor = "[" + String.Format("{0:X6}", random.Next(0x1000000)) + "]; string output = Regex.Replace(input

我想创建一个方法,在字符串中的字符之间插入随机十六进制颜色。这就是我目前所拥有的

`public static string colorString(string input)
{
    var random = new System.Random();
    string hexcolor = "[" + String.Format("{0:X6}", random.Next(0x1000000)) + "];
    string output = Regex.Replace(input, ".{0}", "$0" + hexcolor);
    return ouput;
}`

这使得字符串
“input”
看起来像
[FF0000]I[FF0000]n[FF0000]p[FF0000]u[FF0000]t“
。我如何每次都使hexcode成为一个新的随机数?

您应该将
随机
实例化移到该函数之外(移到类成员中),也可以从调用函数传入

问题是,如果在紧循环中调用该方法(很可能是这样),那么每次都将使用相同的种子创建该方法。因为它具有相同的种子,所以生成的第一个数字对于所有调用都是相同的,显示您的行为

正确的代码是:

Random random = new System.Random();

public static string colorString(string input)
{   
    string hexcolor = "[" + String.Format("{0:X6}", random.Next(0x1000000)) + "];
    string output = Regex.Replace(input, ".{0}", "$0" + hexcolor);
    return ouput;
}

使用相同的
随机对象。