2013-12-10 83 views
-3

我有一个“自动生成”随机数字方法,并将值存储到字符串中。我需要将该变量的值显示在mail.Body属性中。 这是我不得不产生随机数的代码:C#如何将包含值的变量包含到电子邮件正文中作为电子邮件发送

String id = " "; 
Random rnd = new Random(); 

for(int a = 0; a <8; a++){ 
    id += rnd.Next(0,9); 
} 

这是我的邮件正文:

string Body = "Your New Value is " + id ; 
mail.Body = Body; 

但是我收到的电子邮件中只包含“您的新价值”为Body,没有自动生成的值。

我能做些什么来解决这个问题?谢谢!

+4

你试过运行这个例子吗?如果你修正了编译器错误(在第1行添加分号,将第5行的'{'改为'}'),它只是按预期工作。请显示实际上再现问题的工作代码。 – CodeCaster

+0

它没有足够的代码片段来查找错误。 – Arshad

回答

1

试试这个C#-Code

Random rnd = new Random(); 
System.Text.StringBuilder result = new StringBuilder(); 

for (int a = 0; a < 8; a++) 
{ 
    result.Append(rnd.Next(0,9)); 
} 
mail.Body = string.Format("Your New Value is '{0}'", result.ToString()); 

您的代码并没有因为线id += rnd.Next(0,9);的工作。您尝试将int连接到一个字符串。 它应该与这id += rnd.Next(0,9).ToString(); 请不要使用'+'运算符或'+ ='运算符来连接字符串。改用StringBuilder。

+0

这工作完美!非常感谢! – user3081935

0

尝试string.Format

string Body = string.Format("Your New Value is {0}", id); 

而且,你肯定id包含你的期望?

上电话号码的呼叫发电机可能.ToString()帮助:

String id = string.Empty; 
Random rnd = new Random(); 

for(int a = 0; a <8; a++){ 
    id += rnd.Next(0,9).ToString(); { 

另外,+ =每次将字符串...这是你想要做什么?

0
public class GenerateRandomNum 
{ 
    private static string id = ""; 

    public static string RandomNum() 
    { 

    Random rnd = new Random(); 

    for(int a = 0; a <8; a++) 
     { 
     id +=(string)rnd.Next(0,9); 
     } 
    } 
} 

class TestRandom 
{ 
    public static void Main() 
    { 
     string Body = "Your New Value is " + GenerateRandomNum.RandomNum(); 
     mail.Body = Body; 

    } 
} 

希望这将帮助你

相关问题