假设您已经创建了一个类库。在其中您定义了一个 Settings 属性,如下所示:
Properties.Settings.Default.ProjectName
Visual Studio 可能会自动为您生成一些配置,如下所示:
(app.config) </p>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyDllProject.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<MyDllProject.Properties.Settings>
<setting name="ProjectName" serializeAs="String">
<value>MyDllproject</value>
</setting>
</MyDllProject.Properties.Settings>
</applicationSettings>
</configuration>
现在假设您将此程序集添加到项目中。你访问它的设置,你很可能会得到MyDllproject
它的价值。尽管添加了任何配置,但仍然如此。为什么?因为当程序集生成时,它是被写入其中的。并且编写的代码在没有配置覆盖的情况下使用生成时在 app.config 中定义的内容。
现在在您的目标项目中,您只需按照以下模式在配置文件中添加必要的部分
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<!-- start: copied from app.config of class library -->
<section name="MyDllProject.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"
/>
<!-- end: copied from app.config of class library -->
<!-- other sections may follow -->
</sectionGroup>
</configSections>
<applicationSettings>
<!-- remember to maintain the same order as how it was defined in the sectionGroup -->
<!-- start: copied from app.config of class librarly -->
<MyDllProject.Properties.Settings>
<setting name="ProjectName" serializeAs="String">
<value>ConsoleProjectB</value>
</setting>
</MyDllProject.Properties.Settings>
<!-- end: copied from app.config of class library -->
<!-- other configurations settings may follow -->
</applicationSettings>
</configuration>
就是这样。
这是我链接到的一个小项目示例:http: //sdrv.ms/16ksPef