C#中:如何确保一个设置变量试图从另一个程序集使用它之前的存在? [英] C#: How to make sure a settings variable exists before attempting to use it from another assembly?
本文介绍了C#中:如何确保一个设置变量试图从另一个程序集使用它之前的存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下内容:
使用CommonSettings = MyProject.Commons.Settings;
公共类Foo
{
公共静态无效DoSomething的(字符串str)
{
//我如何确保该设置存在第一?
对象设置= CommonSettings.Default [STR]
DoSomethingElse(设置);
}
}
解决方案
根据什么类型的 CommomSettings.Default
是,一个简单的空检查要细:
如果(!设置= NULL)
DoSomethingElse(设置);
如果你想检查之前试图恢复设置,您需要张贴CommonSettings的类型。默认。它看起来像一个字典,所以你也许能蒙混过关:
如果(CommonSettings.Default.ContainsKey(STR))
{
DoSomethingElse(CommonSettings.Default [STR]);
}
I have the following:
using CommonSettings = MyProject.Commons.Settings;
public class Foo
{
public static void DoSomething(string str)
{
//How do I make sure that the setting exists first?
object setting = CommonSettings.Default[str];
DoSomethingElse(setting);
}
}
解决方案
Depending on what type CommomSettings.Default
is, a simple null check should be fine:
if(setting != null)
DoSomethingElse(setting);
If you want to check BEFORE trying to retrieve the setting, you need to post the Type of CommonSettings.Default. It looks like a Dictionary so you might be able to get away with:
if(CommonSettings.Default.ContainsKey(str))
{
DoSomethingElse(CommonSettings.Default[str]);
}
这篇关于C#中:如何确保一个设置变量试图从另一个程序集使用它之前的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文