C# 属性 - 获取编译时默认值



我正在使用C#和Visual Studio的"设置"功能来管理我的应用程序设置。当然,这些可以被 XML 覆盖。

但是,我想要一种方法来检索我在Visual Studio中设置的编译时默认值

Properties.Settings.Defaults.MyProp

无法实现此目的 - 它返回从 XML 中选取的任何内容。有没有办法保证检索在开发过程中在"设置"页面中键入的任何内容?

上下文是我的某些设置非常具体,因此我的应用程序会验证它们以确保它们在参数范围内,如果不是,我希望能够故障回复到默认值。

这似乎是获取属性的原始编译时值的唯一途径。可惜它不是强类型化的

Properties.Settings.Default.Properties["name"].DefaultValue as string;

Settings类型只是一个自动生成的internal sealed partial class,因此没有任何理由不能添加一个名为Defaults的新static属性,该属性可以满足您的需求。

// In some file, perhaps called Settings.Defaults.cs?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YourApplication.Properties
{
internal sealed partial class Settings
{
public static SettingsDefaults Defaults
{
get { return _defaults; }
}
internal class SettingsDefaults
{
public int NumberBetween1And100
{
get
{
// Or just hardcode it and come here and change it if you change the default value.
return (int)Settings.Default.Properties["NumberBetween1And100"].DefaultValue;
}
}
}
private static readonly SettingsDefaults _defaults = new SettingsDefaults();
}
}

您可以像在问题中描述的那样使用它:Properties.Settings.Defaults.NumberBetween1And100.

这并不完美。例如,如果从设置设计器添加新设置,则必须记住进入此文件并将新属性添加到SettingsDefaults类中。此外,Properties.Settings.DefaultProperties.Settings.Defaults的名称非常相似,以至于感觉可能是错误的来源。

最新更新