【问题标题】:Programatically determine if settings is per User or per Application以编程方式确定设置是按用户还是按应用程序
【发布时间】:2015-08-11 15:32:04
【问题描述】:

给定一个任意设置参数 EG Properties.Settings.Default.ArbitraryParam,您能否以编程方式从应用程序中判断这是针对每个用户还是每个应用程序设置?

或者,鉴于每个应用程序设置是只读的,防止尝试写入每个应用程序设置的最佳做法是什么?或者在调用Properties.Settings.Default.Save() 时除了没有更新值之外什么都不会发生?

【问题讨论】:

  • 你的问题很混乱。你能澄清你在问什么吗?
  • @xxbbcc 为什么你认为它令人困惑? properties.settings.default.xxxx 是 C# 项目中众所周知的一部分。我能做的就是写一篇关于这是什么的教程。
  • 嗯,根据msdn.microsoft.com/en-US/library/Aa730869%28v=VS.80%29.aspx,调用Properties.Settings.Default.Save()会保存用户设置。

标签: c# .net application-settings settings


【解决方案1】:

如果你想确定它们是用户作用域还是应用程序作用域,你可以写一点扩展方法...

public static class SettingsExtensions
{
    public bool IsUserScoped(this Settings settings, string variableName)
    {
        PropertyInfo pi = settings.GetType().GetProperty(variableName, BindingFlags.Instance);

        return pi.GetCustomAttribute<System.Configuration.UserScopedSettingAttribute>() != null;
    }
}

然后调用:

Settings.Default.IsUserScoped("SomeVariableName");

如果您想从属性中获取实际名称,您可以做更多的技巧,但它显示了一种方法。另一种方法是确定属性是否包含getset 访问器(用户范围)或仅包含get(应用程序范围)。

如果你打开 Settings.Designer.cs 文件就很清楚了,这是我的示例文件:

[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

    public static Settings Default {
        get {
            return defaultInstance;
        }
    }

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("blah")]
    public string UserSetting {
        get {
            return ((string)(this["UserSetting"]));
        }
        set {
            this["UserSetting"] = value;
        }
    }

    [global::System.Configuration.ApplicationScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("hardy har har")]
    public string AppSetting {
        get {
            return ((string)(this["AppSetting"]));
        }
    }
}

注意属性?它们可用于确定有关属性的信息。

但是,另一个很好的判断方法是,如果你写了

Settings.Default.SomeAppSetting = some_value;

你会得到一个编译器错误,因为没有设置访问器。

【讨论】:

  • 当我看到你关于没有设置访问者的评论时,我有一个很好的时刻。我一直在考虑使用包装器来抽象设置功能(以便通过隐藏实现来使事情更便携),并且缺少设置访问器意味着我无法以编程方式处理用户与应用程序设置,并且将拥有根据具体情况手动处理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
  • 2011-09-27
  • 2016-11-09
  • 1970-01-01
  • 2015-04-12
相关资源
最近更新 更多