将元数据附加到无法更改的对象的属性?

时间:2019-07-11 12:58:09

标签: c# data-structures

对于既可以包含原始数据类型又可以包含复杂类数据类型的给定Dictionary(字符串到对象),需要能够为某些Properties(可能嵌套)添加附加信息,而无需更改字典中存在的数据结构,并能够按属性获取此元数据以供以后使用。 另外,应保留此元数据以供以后使用,而不是仅在运行时保留,因此使用引用是有问题的。

我尝试过的解决方案是在字典中保存其他元数据KeyValuePair。例如,将数据对象地址的Street属性定义为特殊和重要,将添加以下信息

{ "root.Data.Address.Street", new Dictionary<string, object>()
            {
                { "special", true },
                { "important", true }
            }}

要查询该属性的元数据信息,我们将在字典的根目录中搜索该属性的路径。

一个例子:

//The data in the dictionary can't be changed or wrapped in some way
Dictionary<string, object> dataObject = new Dictionary<string, object>()
        {
            { "Name", "name123"},
            { "Addresses", new List<Address>()
                {
                    new Address("A", "B", 1),
                    new Address("C", "D", 2)
                }
            },
            {"Data", new Data("123Name", new Address("E", "F", 3))}
        };

//Can't be changed
public class Data
{
    public string Name { get; }
    public Address Address { get; }

    public Data(string name, Address address)
    {
        Name = name;
        Address = address;
    }
}

//Can't be changed
public class Address
{
    public string City { get; }
    public string Street { get; }
    public int Number { get; }

    public Address(string city, string street, int number)
    {
        City = city;
        Street = street;
        Number = number;
    }
}

预期的行为是能够查询尽可能接近以下数据的数据:

dataObject["Data"].Address.Street.special == true
dataObject["Data"].Address.City.important == false

欢迎任何想法

0 个答案:

没有答案