如何使TableEntity序列化非公共属性?

时间:2018-02-23 15:05:31

标签: c# .net azure serialization azure-table-storage

Azure表存储有一些令人沮丧的限制,例如无法处理decimal数据类型,所以我必须这样做:

public class MyEntity : TableEntity {
        [IgnoreProperty]
        public decimal ListPrice
        {
            get => decimal.Parse(this.ListPrice_, CultureInfo.InvariantCulture);
            set => this.ListPrice_ = value.ToString(CultureInfo.InvariantCulture);
        }

        public string ListPrice_ { get; set; }
}

显然,我不希望ListPrice_成为public,但SDK似乎忽略了private个成员。是否有任何简单的技巧可以使其序列化非公开成员(没有反思)?

1 个答案:

答案 0 :(得分:1)

我不知道可用于序列化TableEntity的非公开属性的任何属性,但您可以覆盖interface {的ReadEntityWriteEntity方法{3}}自定义您自己的属性序列化。

public class MyEntity : TableEntity
{
    [IgnoreProperty]
    public decimal ListPrice
    {
        get => decimal.Parse(this.ListPrice_, CultureInfo.InvariantCulture);
        set => this.ListPrice_ = value.ToString(CultureInfo.InvariantCulture);
    }

    private string ListPrice_ { get; set; }

    public override void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
    {
        this.ListPrice_ = properties[nameof(ListPrice)].StringValue;
    }

    public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
    {
        var properties = new Dictionary<string, EntityProperty>();
        properties.Add(nameof(ListPrice), new EntityProperty(this.ListPrice_));
        return properties;
    }
}