实现通用设置类的最佳方法 - 反映获取/设置属性?

时间:2013-01-16 13:25:43

标签: c# xml reflection properties settings

我不知道如何制作通用设置课,希望你能帮助我 首先,我想要一个单一的设置文件解决方案。为此,我创建了一个像这样的单身人士:

public sealed class Settings
{
  private static readonly Lazy<Settings> _instance = new Lazy<Settings>(() => new Settings());
  private Dictionary<string, object> m_lProperties = new Dictionary<string, object>();

  public void Load(string fileName)
  {
    throw new NotImplementedException();  
  }

  public void Save(string fileName)
  {
    throw new NotImplementedException();
  }

  public void Update()
  {
    throw new NotImplementedException();
  }

  /// <summary>
  /// Gets the propery.
  /// </summary>
  /// <param name="propertyName">Name of the property.</param>
  /// <returns></returns>
  public string GetPropery(string propertyName)
  {
    return m_lProperties[propertyName].ToString() ?? String.Empty;
  }

  /// <summary>
  /// Gets the propery.
  /// </summary>
  /// <param name="propertyName">Name of the property.</param>
  /// <param name="defaultValue">The default value.</param>
  /// <returns></returns>
  public string GetPropery(string propertyName, string defaultValue)
  {
    if (m_lProperties.ContainsKey(propertyName))
    {
      return m_lProperties[propertyName].ToString();
    }
    else
    {
      SetProperty(propertyName, defaultValue);
      return defaultValue;
    }
  }

  /// <summary>
  /// Sets the property.
  /// </summary>
  /// <param name="propertyName">Name of the property.</param>
  /// <param name="value">The value.</param>
  public void SetProperty(string propertyName, string value)
  {
    if (m_lProperties.ContainsKey(propertyName))
      m_lProperties[propertyName] = value;
    else
      m_lProperties.Add(propertyName, value);
  }
}

但我认为更好的方法是属性在类中,我可以通过反射获得属性 - 你能帮我实现这样的事吗? - 是否可以提供“encrypted = true”等属性属性? - 什么是在xml文件中保存/加载设置的最佳方法?

更新
以下是如何使用实际设置的示例:

class Test()
{
  private string applicationPath;
  private string configurationPath;
  private string configurationFile;

  public Test()
  {
    applicationPath = Settings.Instance.GetPropery("ApplicationPath", AppDomain.CurrentDomain.BaseDirectory);
    configurationPath = Settings.Instance.GetPropery("ConfigurationPath", "configurations");  
    configurationFile = Settings.Instance.GetPropery("ConfigurationFile", "application.xml");  
    // ... Load file with all settings from all classes
  } 

4 个答案:

答案 0 :(得分:2)

这是我自己的代码中相当重要的一点。

public class MyObject
{
    public string StringProperty {get; set;}

    public int IntProperty {get; set;}

    public object this[string PropertyName]
        {
            get
            {
                return GetType().GetProperty(PropertyName).GetGetMethod().Invoke(this, null);
            }
            set
            {
                GetType().GetProperty(PropertyName).GetSetMethod().Invoke(this, new object[] {value});
            }
        }
}

它允许的是:

MyObject X = new MyObject();
//Set
X["StringProperty"] = "The Answer Is: ";
X["IntProperty"] = 42;
//Get - Please note that object is the return type, so casting is required
int thingy1 = Convert.ToInt32(X["IntProperty"]);
string thingy2 = X["StringProperty"].ToString();

更新:更多解释 这种方式的工作方式是反射访问属性,属性与字段的不同之处在于它们使用getter和setter,而不是直接声明和访问。您可以使用相同的方法来获取字段,或者使用获取字段,如果您从GetProperty返回null,而不是简单地假设它有效。另外,正如在另一条评论中指出的那样,如果你用一个不存在的属性来调用它,这将会中断,因为它没有任何形式的错误捕获。我以最简单的形式展示了代码,而不是最强大的形式。

至于属性属性....需要在类中创建索引器(或者是父类,我在BaseObject上使用它),所以在内部你可以实现给定属性上的属性,然后在访问属性时对属性应用开关或检查。也许将所有属性设置为实现Object Value; Bool Encrypted;的其他自定义类,然后根据需要对其进行处理,这实际上取决于您想要获得多少花哨以及想要编写多少代码。

答案 1 :(得分:1)

我不建议在没有它的情况下使用Reflection,因为它非常慢。

我的例子没有反射和加密原型:

public sealed class Settings
{
    private static readonly HashSet<string> _propertiesForEncrypt = new HashSet<string>(new string[] { "StringProperty", "Password" });
    private static readonly Lazy<Settings> _instance = new Lazy<Settings>(() => new Settings());
    private Dictionary<string, object> m_lProperties = new Dictionary<string, object>();

    public void Load(string fileName)
    {
        // TODO: When you deserialize property which contains into "_propertiesForEncrypt" than Decrypt this property.
        throw new NotImplementedException();
    }

    public void Save(string fileName)
    {
        // TODO: When you serialize property which contains into "_propertiesForEncrypt" than Encrypt this property.
        throw new NotImplementedException();
    }

    public void Update()
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Gets the propery.
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    /// <returns></returns>
    public object GetPropery(string propertyName)
    {
        if (m_lProperties.ContainsKey(propertyName))
            return m_lProperties[propertyName];

        return null;
    }

    /// <summary>
    /// Gets the propery.
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    /// <param name="defaultValue">The default value.</param>
    /// <returns></returns>
    public object GetPropery(string propertyName, object defaultValue)
    {
        if (m_lProperties.ContainsKey(propertyName))
        {
            return m_lProperties[propertyName].ToString();
        }
        else
        {
            SetProperty(propertyName, defaultValue);
            return defaultValue;
        }
    }

    /// <summary>
    /// Sets the property.
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    /// <param name="value">The value.</param>
    public void SetProperty(string propertyName, object value)
    {
        if (m_lProperties.ContainsKey(propertyName))
            m_lProperties[propertyName] = value;
        else
            m_lProperties.Add(propertyName, value);
    }


    // Sample of string property
    public string StringProperty
    {
        get
        {
            return GetPropery("StringProperty") as string;
        }
        set
        {
            SetProperty("StringProperty", value);
        }
    }

    // Sample of int property
    public int IntProperty
    {
        get
        {
            object intValue = GetPropery("IntProperty");
            if (intValue == null)
                return 0; // Default value for this property.

            return (int)intValue;
        }
        set
        {
            SetProperty("IntProperty", value);
        }
    }
}

答案 2 :(得分:0)

使用这样的动态类:https://gist.github.com/3914644,这样您就可以访问属性:yourObject.stringProperty或yourObject.intProperty

答案 3 :(得分:0)

最大的问题之一是没有干净的方法将对象反序列化为对象。如果您不提前知道对象的类型需要什么,那么它很难处理。所以我们有一个替代解决方案,存储类型信息。

鉴于未列出,我将提供我认为的示例XML,以及使用它的方法,以及访问属性本身的方法。您用于获取和设置属性的功能按原样运行,不需要更改。

在各个类中,您需要确保该类中的相关属性在其自己的get / set方法中引用Settings类

public int? MyClassProperty
{
    get
    {
        return (int?)Settings.Instance.GetProperty("MyClassProperty");
    }
    set
    {
        Settings.Instance.SetProperty("MyClassProperty", value);
    }
}

在加载和保存功能中,您将需要使用序列化,特别是XmlSerializer。为此,您需要适当地声明您的设置列表。为此,我实际上会使用自定义类。

已更新以允许正确加载

public class AppSetting
{
    [XmlAttribute("Name")]
    public string Name { get; set; }
    [XmlAttribute("pType")]
    public string pType{ get; set; }
    [XmlIgnore()]
    public object Value{ get; set; }
    [XmlText()]
    public string AttributeValue 
    {
        get { return Value.ToString(); }
        set {
        //this is where you have to have a MESSY type switch
        switch(pType) 
        { case "System.String": Value = value; break;
          //not showing the whole thing, you get the idea
        }
    }
}

然后,您将拥有类似于:

的内容,而不仅仅是字典
public sealed class Settings
{
  private static readonly Lazy<Settings> _instance = new Lazy<Settings>(() => new Settings());
  private Dictionary<string, object> m_lProperties = new Dictionary<string, object>();
  private List<AppSetting> mySettings = new List<AppSetting>();

你的加载函数将是一个简单的反序列化

public void Load(string fileName)
{//Note: the assumption is that the app settings XML will be defined BEFORE this is called, and be under the same name every time.
    XmlSerializer ser = new XmlSerializer(typeof(List<AppSetting>));
    FileStream fs = File.Open(fileName);
    StreamReader sr = new StreamReader(fs);
    mySettings = (List<AppSetting>)ser.DeSerialize(sr);
    sr.Close();
    fs.Close();

    //skipping the foreach loop that will add all the properties to the dictionary
}

保存功能基本上需要反转它。

public void Save(string fileName)
    {
        //skipping the foreach loop that re-builds the List from the Dictionary
        //Note: make sure when each AppSetting is created, you also set the pType field...use Value.GetType().ToString()

        XmlSerializer ser = new XmlSerializer(typeof(List<AppSetting>));
        FileStream fs = File.Open(fileName, FileMode.Create);
        StreamWriter sw = new StreamWriter(fs);
        //get rid of those pesky default namespaces
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        ser.Serialize(sw, mySettings, ns);
        sw.Flush();
        sw.Close();
        fs.Close();
        mySettings = null;//no need to keep it around
    }

并且xml会像这样:

<强>更新

<ArrayOfAppSetting>
    <AppSetting Name="ApplicationPath" pType="System.String">C:\Users\ME\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\</AppSetting> 
    <AppSetting Name="ConfigurationPath" pType="System.String">configurations</AppSetting> 
    <AppSetting Name="ConfigurationFile" pType="System.String">application.xml</AppSetting> 
    <AppSetting Name="prop" pType="System.Int32">1</AppSetting> 
</ArrayOfAppSetting>

我使用中间List<>展示了这个例子,因为事实证明你不能使用任何用XmlSerializer实现IDictionary的东西。它将无法初始化,它只是不起作用。

您可以在字典旁边创建和维护列表,也可以使用列表替换字典...确保您有检查以验证“名称”是唯一的,或者您可以忽略列表,除非在保存和加载操作(这是我写这个例子的方式)

<强>更新 这真的只适用于与原始类型(int,double,string等),但因为你直接存储类型,你可以使用你想要的任何自定义类型,因为你知道它是什么如何处理它,你只需要在AttributeValue

的set方法中处理它

另一个更新:如果您只存储字符串,而不是所有类型的对象......它会变得非常简单。摆脱XmlIgnore valuepType,然后自动实施AttributeValue。热潮,完成了。这将限制你使用字符串和其他基元,确保其他类中的值的Get / Set正确地投射它们......但这是一个更简单和更容易的实现。