在C#中为对象指定动态属性

时间:2014-02-24 10:14:21

标签: c# sql-server solr

我正在寻找一种最佳实践来保存对象的动态属性集。我们的想法是拥有一个基础对象Person,并允许用户向其添加属性。

例如,我有一个具有FirstNameLastName基本属性的Person。 User1会将HairColor添加为stringUser2会将Height添加为int

关键是允许用户获取核心对象并动态添加属性以满足他们的需求,然后我希望将其持久保存到DB并允许搜索这些属性(MSSQL和{{1 }})。

3 个答案:

答案 0 :(得分:3)

来自.Net 4.0有ExpandoObject - 这将是您的选择!

在.Net 4.0之前你可以用一个隐藏的Dictionary<string, object>包装一个很好的类来保存你的属性

编辑示例代码

在下面的示例中,我们创建了一个具有一些已知属性和可扩展ExtraProperties

的类

最后,我们可以迭代ExpandoObject来获取所有动态添加的值:

注意:ExpandoObject实施IEnumerable<KeyValuePair<string, object>>

class Program
{
    static void Main(string[] args)
    {
        Person p1 = new Person();
        p1.ExtraProperties.HairColor = "Green";
        p1.ExtraProperties.DateOfGraduation = DateTime.UtcNow;    

        foreach (var prop in p1.ExtraProperties)
        {
            Console.WriteLine(prop.Key + ": " + prop.Value);
        }

    }
}

public class Person
{
    private System.Dynamic.ExpandoObject _extraProperties = new System.Dynamic.ExpandoObject();

    public string Name { get; set; }
    public DateTime BornDate { get; set; }

    public dynamic ExtraProperties
    {
        get { return _extraProperties; }
    }

}

答案 1 :(得分:3)

要将Expando对象变为Solr,您可以使用完全松散映射的Sornet。

答案 2 :(得分:1)

我有一个类似的用例我用这个类解决了

public class User
{
    #region Private Fields

    private readonly Dictionary<string, string> _keyValues = new Dictionary<string, string>();

    #endregion

    #region Public Properties

    /// <summary>
    ///     Gets the field names.
    /// </summary>
    /// <value>
    ///     The field names.
    /// </value>
    public IEnumerable<string> FieldNames
    {
        get { return _keyValues.Keys; }
    }

    #endregion

    #region Public Methods

    /// <summary>
    ///     Gets or sets the <see cref="System.String" /> for the specified fieldName.
    /// </summary>
    /// <value>
    ///     The <see cref="System.String" />.
    /// </value>
    /// <param name="fieldName">The field name.</param>
    /// <returns>The value for the field if it could be found; otherwise null</returns>
    public string this[string fieldName]
    {
        get
        {
            string value;
            return _keyValues.TryGetValue(fieldName, out value) ? value : null;
        }
        set { _keyValues.Add(fieldName, value); }
    }

    /// <summary>
    ///     Returns a <see cref="System.String" /> that represents this instance.
    /// </summary>
    /// <returns>
    ///     A <see cref="System.String" /> that represents this instance.
    /// </returns>
    public override string ToString()
    {
        string res = string.Empty;
        foreach (KeyValuePair<string, string> pair in _keyValues)
        {
            res += string.Format("{0}={1};", pair.Key, pair.Value);
        }
        return res.TrimEnd(';');
    }

    #endregion
}

请注意,在这种情况下,所有属性都是string类型。可以使用索引器访问所有属性,例如,用户[ “名称”]

相关问题