我在c#console应用程序中有一些公共const字符串,如下所示:
//Account one
public const string POP_USER1 = "abc@abcd.com";
public const string POP_PWD1 = "abc";
//Account two
public const string POP_USER2 = "xyz@abcd.com";
public const string POP_PWD2 = "xyz";
//Account three
public const string POP_USER3 = "pqr@abcd.com";
public const string POP_PWD3 = "pqr;
我们正在使用c#MailMan来检索这些帐户中的电子邮件。 我简单地写了3次for循环:
for (int i = 1; i <= 3; i++)
{
eEmails obj = new eEmails (i);
}
在eEmails的构造函数中,我写的是以下逻辑:
public eEmails (int counter)
{
MailMan obj = new MailMan()
obj.PopUsername = "POP_USER" + counter;
obj.PopPassword = "POP_PWD" + counter;
}
我分配用户名和密码的行,我需要获取确切的const变量(即POP_USER1,POP_USER2,POP_USER3等)
但是我无法动态获取变量。 我可以简单地在eEmails(int counter)中编写3个块,但我不喜欢这样。 有人可以建议一种更好的方法来处理这种情况,而不为每个用户使用单独的if块吗?
答案 0 :(得分:2)
使用类而不是strings
,然后您的代码变得更易于修改和维护,并且它也更不容易出错。以下是使用List<PopServerAccount>
作为容器的示例:
public class PopServerAccount
{
public string Username {get;set;}
public string Password {get;set;}
public override bool Equals(object obj)
{
PopServerAccount p2 = obj as PopServerAccount;
if (p2 == null) return false;
return Username == p2.Username;
}
public override int GetHashCode()
{
return Username.GetHashCode();
}
public override string ToString()
{
return Username;
}
}
现在更改方法的签名:
public eEmails (PopServerAccount pop)
{
MailMan obj = new MailMan()
obj.PopUsername = pop.Username;
obj.PopPassword = pop.Password;
}
示例数据:
var myPopServers = new List<PopServerAccount>
{
new PopServerAccount{ Username = "abc@abcd.com", Password = "abc"},new PopServerAccount{ Username = "xyz@abcd.com", Password = "xyz"}
};
使用循环并调用您的方法:
foreach (PopServerAccount pop in myPopServers)
{
eEmails(pop);
}