【问题标题】:Simulating multiple inheritance with TableEntity使用 TableEntity 模拟多重继承
【发布时间】:2019-09-07 12:52:55
【问题描述】:

我读到 C# 中不存在多重继承,但 can be mocked by using interfaces

我正在尝试做类似的事情,但它似乎不起作用。想知道我可能做错了什么。我已经定义了要继承自的具体类:

public class AppSettings {
    public string CosmosDbPrimaryKey {get; set;}
}

然后是直接从AppSettings 继承并实现ITableEntity 的“超级”类。这个类最终应该像继承自 AppSettings 和 TableEntity 一样。

public class AppSettingsRow: AppSettings, ITableEntity
    {
        private readonly TableEntity _tableEntity;
        public AppSettingsRow()
        {
            _tableEntity = new TableEntity();
        }

        public string PartitionKey { get; set; }
        public string RowKey { get; set; }
        public DateTimeOffset Timestamp { get; set; }
        public string ETag { get; set; }

        public void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
        {
            _tableEntity.ReadEntity(properties, operationContext);
        }

        public IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            return _tableEntity.WriteEntity(operationContext);
        }
    }

问题是,当我实际使用表中的类和列表行时,AppSettings 字段显示为空。

如果我这样做 相反 并直接从 TableEntity 继承并实现 AppSettings 它工作得很好,但这对我来说并不理想。 AppSettings 可能会随着时间而变化,我不想每次发生变化时都必须维护两个独立的模型。

我做错了什么?

【问题讨论】:

  • 为什么要多重继承?对我来说,您似乎正在尝试创建一个有 2 个目的的课程,这与 单一职责原则 (SRP) 相悖。
  • 我不想维护两个独立的模型但是你仍然想要两个有两个独立的类??

标签: c# azure azure-table-storage


【解决方案1】:

TableEntity 的实现使用反射来枚举具体类型的可序列化属性。在这种情况下,您根本不需要从TableEntity 继承,只需实现自己的序列化即可。考虑在 ReadEntity 方法中调用 TableEntity.ReadUserObject(this, properties, operationContext)

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2017-03-31
    • 2010-12-11
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多