如何动态使用不同的数据型填充值? C#
我制作了一个SMTP控制台应用程序,现在我试图将所有检查放在一起,以避免使用过多的“几乎”重复if语句。
因此,我做了一个foreach循环,以尝试使用AppConfig文件填充我在开始实现的所有值。
int port = 0;
bool useCredentials = false;
string username = "";
string password = "";
bool useSsl = false;
string receiver = "";
string sender = "";
string subject = "";
string body = "";
bool error = false;
string[] values = { "smtpServer", "port", "useCredentials", "username", "password", "useSsl", "receiver", "sender", "subject", "body" };
foreach(var val in values)
{
if (ConfigurationManager.AppSettings[val] == null || ConfigurationManager.AppSettings[val].Length == 0)
{
Console.WriteLine(val+" is null");
error = true;
}
else
{
{
//i want the val to be filled, so first smtpServer then port then useCredentials and so on...
val = ConfigurationManager.AppSettings[val]?.ToString();
}
Console.WriteLine(val);
}
}
如何填充我在顶部实现的每个字段的值?
I made an SMTP Console Application and now i'm trying to put all checks together to avoid too many "almost" repetitive if statements.
So I made a foreach loop to try to fill all the values I implemented at the beginning with an AppConfig file.
int port = 0;
bool useCredentials = false;
string username = "";
string password = "";
bool useSsl = false;
string receiver = "";
string sender = "";
string subject = "";
string body = "";
bool error = false;
string[] values = { "smtpServer", "port", "useCredentials", "username", "password", "useSsl", "receiver", "sender", "subject", "body" };
foreach(var val in values)
{
if (ConfigurationManager.AppSettings[val] == null || ConfigurationManager.AppSettings[val].Length == 0)
{
Console.WriteLine(val+" is null");
error = true;
}
else
{
{
//i want the val to be filled, so first smtpServer then port then useCredentials and so on...
val = ConfigurationManager.AppSettings[val]?.ToString();
}
Console.WriteLine(val);
}
}
How can i fill the value for each field i implemented at the top?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,我认为您需要将主意转变为客观的编程。
创建类:
并且不使用foreach,您不需要。您想将您的配置对此对象进行验证,因此:
然后可以将其用作
appSettings.port
Okay i think you need to change your mind to objective programming.
Create class:
And do not use foreach, you dont need that. You want to Deserialize your configuration to this object, so:
and then you can use it as
appSettings.port