【发布时间】:2016-11-09 07:17:21
【问题描述】:
你能帮我解决两个或一个问题吗,不确定。我正在尝试从多个 private static string 中获取字符串和整数值,其中包含不同的进程,每个进程都有一个不同类型的输出,我希望将它们作为函数顺序返回以进行进一步组合。
首先我想说我不知道,如果下面的方法是错误的,如何创建这样的函数,它可以返回值以获得所需的结果,并且很高兴看到一些有用的例子,但是什么我在这里尝试做,给我两个问题:
如果我想调用b1,然后是b2,然后再调用b1,我想从每个人那里得到唯一的计算结果,但现在我得到了相同的结果,如果我使用如下所示的随机数,但我怀疑在这种情况下,这个问题的原因是在private static string 中错误地使用了随机数,还需要弄清楚如何在这种情况下正确使用它。
结果如下所示:
23 23 23
但我也认为这不仅仅是一个相同的主要问题,因为如果我返回一些不同的计算结果,例如在私有静态字符串 b1 和 b2 中分别从不同列表的不同字符串集中选择,结果只是按顺序调用的顺序重复处理两次或多次返回相同的值。我不能肯定地说,但它看起来不像是同样的问题原因,可以在上面。因为它看起来像这样:
77 34 77
或者为了更清楚,如果我通过计算表单字符串选择一些单词,例如:"hello world, how are you" 并且在每个private static string 内部我会进行不同的计算以获得单个单词从这个字符串,或从不同的任何人,我得到了相同的结果或正确地说相同的结果,两次调用相同的过程,就像重复结果而不是单独调用它:
world you world
下面这个例子只展示了随机数的情况,因为如果最后一个问题不同并且与使用错误的随机数没有关系,原因必须是一般的方法,我应该以不同的方式解决这个问题。
class Program
{
static void Main(string[] args)
{
string a1 = b1();
string a2 = b2();
string a3 = b1();
string comb = (a1 + a2 + a3);
Console.WriteLine(comb);
Console.ReadLine();
}
private static string b1()
{
Random random = new Random();
int ran1 = random.Next(1, 100);
return ran1;
}
private static string b2()
{
Random random = new Random();
int ran2 = random.Next(1, 100);
return ran2;
}
}
编辑 1:
通过随机数或任何其他方式选择字符串返回的示例:
static void Main(string[] args)
{
string a1 = b1();
string a2 = b2();
string a3 = b1();
string comb = (a1 + a2 + a3);
Console.WriteLine(comb);
Console.ReadLine();
}
private static string b1()
{
Dictionary<int, string> mass1 = new Dictionary<int, string>()
{ { 1, "A" }, { 2, "B" }, { 3, "C" }};
Random random1 = new Random();
int rndCase2 = random1.Next(1, 4);
string key1;
mass1.TryGetValue(rndCase2, out key1);
return key1;
}
private static string b2()
{
Dictionary<int, string> mass2 = new Dictionary<int, string>()
{ { 1, "E" }, { 2, "F" }, { 3, "G" }};
Random random2 = new Random();
int rndCase2 = random2.Next(1, 4);
string key2;
mass2.TryGetValue(rndCase2, out key2);
return key2;
}
结果是:
AEA
编辑 2:(已解决)
class Program
{
private static Random random = new Random();
static void Main(string[] args)
{
string a1 = b1();
string a2 = b2();
string a3 = b1();
string comb = (a1 + a2 + a3);
Console.WriteLine(comb);
Console.ReadLine();
}
private static string b1()
{
Dictionary<int, string> mass1 = new Dictionary<int, string>()
{ { 1, "A" }, { 2, "B" }, { 3, "C" }};
return mass1[random.Next(1, 4)];
}
private static string b2()
{
Dictionary<int, string> mass2 = new Dictionary<int, string>()
{ { 1, "E" }, { 2, "F" }, { 3, "G" }};
return mass2[random.Next(1, 4)];
}
}
【问题讨论】:
-
我很确定
string comb = (a1 + a2 + a1);这行有错字,必须是string comb = (a1 + a2 + a3);(注意最后的a3) -
@DefColin:对不起,我没有遵循最后一句话“但例如较新的 AFB,似乎重复调用不仅返回与随机数相同的结果,而且返回相同的结果。”,请你换一种说法。例如,您的
A是否比预期的太很多 / 太很少?是否怀疑该序列是倾斜的? -
@DefColin:您似乎想要
string comb = (a1 + a2 + a3);(请注意a3),而不是string comb = (a1 + a2 + a1);(请注意第二个a1) -
@Dmitry Bychenko 哦,是的,我确信没有错字,但它就在那里,我的错,现在一切都好。下面的两个答案都有效。谢谢。
-
@Hans Kesting 是的,确实在那里,已编辑。
标签: c# string function random return-value