简体   繁体   English

从Class访问Properties.Settings.Default?

[英]Accessing Properties.Settings.Default from Class?

When I create a Console App I can right click on the project in Visual Studio 2008 Pro. 当我创建一个控制台应用程序时,我可以在Visual Studio 2008 Pro中右键单击该项目。 click Properties > Go To Settings enter a Application Scope Setting and then access it from code like 单击属性>转到设置,输入应用程序范围设置,然后从代码中访问它

Console.WriteLine(Properties.Settings.Default.MySetting.ToString());

When I do the same thing in a Class Project and try to assign the the Applicatin Scope Setting to a variable like 当我在类项目中做同样的事情并尝试将Applicatin范围设置分配给变量之类的

this.mySettingVariable = Properties.Settings.Default.MySetting.ToString();

I get an the error when building that "The name 'Properties' does not exist in the current context." 在构建“当前上下文中不存在名称'属性'时,我收到错误。”

What am I doing wrong and how can I access the Application Scoped properties for a class project? 我做错了什么以及如何访问类项目的Application Scoped属性?

You forgot to add settings to the class library project. 您忘了将设置添加到类库项目中。 You cannot access the settings of the EXE project directly. 您无法直接访问EXE项目的设置。

Giving a class library project its own settings is possible but it is a hassle. 给一个类库项目自己的设置是可能的,但这是一个麻烦。 A DLL cannot have its own .config file, there's only one: the app.exe.config file. DLL不能拥有自己的.config文件,只有一个:app.exe.config文件。 You have to merge the entries in the DLL's app.config file into the app.exe.config file by hand. 您必须手动将DLL的app.config文件中的条目合并到app.exe.config文件中。 Copy and paste with a text editor. 使用文本编辑器复制和粘贴。 This is not very maintainable. 这不是很容易维护。

Another approach is to make these settings properties of the class. 另一种方法是使类的这些设置属性。 And let the code in the main project initialize them from its own settings. 让主项目中的代码从它自己的设置初始化它们。 Or just ditch settings because their a pita and use an .xml file. 或者只是放弃设置,因为他们的皮塔饼并使用.xml文件。

Make sure you have included the namespace in the 'usings'. 确保在'usings'中包含了名称空间。

Also make sure the settings class is public. 还要确保设置类是公共的。

Pulled from here 这里拉出来

Because there is no configuration file model for class libraries, application settings do not apply for Class Library projects. 由于类库没有配置文件模型,因此应用程序设置不适用于类库项目。 The exception is a Visual Studio Tools for Office DLL project, which can have a configuration file. Office DLL项目的Visual Studio工具是一个例外,它可以有一个配置文件。

您的.settings文件是否在项目的Properties文件夹下?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM