C# DTO 计算 属性

C# DTO with calculated property

我有一些 DTO 需要保存到 redis,我希望它们都有一个 属性 或生成 redis 键的方法。

public class Product
{
   public string Name {get; set;}
   public string Type {get; set;}

   // Use Property (Maybe Inherit a base class or interface)
   public string CacheKey
   {
      get
      {
         return Type + "_" + Name;
      }
   }

   // User Method (Maybe Inherit a base class or interface)
   public string GetCacheKey()
   {
      return Type + "_" + Name;
   }
}

或者...我不应该将它们添加到DTO,但我希望所有需要保存到redis的DTO都必须有一个密钥,并且每个密钥都是由其自身属性生成的。

有人可以给我一些建议吗?

观察 Open-Closed Principle of the SOLID principles

你不应该改变 DTO 的既定目的(正如@GlennvanAcker 所说,DTO 没有逻辑)。

但是,我们可以给它一个扩展方法...这是我的建议。

    public static class ProductExtensions
    {
        public static string CacheKey(this Product product)
        {
            return product.Type + "_" + product.Name;
        }
    }

@HansKesting 指出我没有说明如何使 classes 除了 Product...

这需要我们扩展基础 class 或接口。如果这个方法要应用到多个classes;编译器需要知道 class 具有所需的属性(类型和名称):

例如

// I'm not calling this interface IDto because I am not assuming that all DTOs have these properties.
public interface IDtoWithTypeAndName
{
    public string Type { get; set; }
    public string Name { get; set; }
}

public static class DtoExtensions
{
    public static string CacheKey(this IDtoWithTypeAndName dto)
    {
        return dto.Type + "_" + dto.Name;
    }
}
public class Product : IDtoWithTypeAndName
{
    public string Type { get; set; }
    public string Name { get; set; }
}

我们必须在这里考虑务实。在这种情况下,缓存键 getter 函数的实现不是真正的业务逻辑。

我的建议是,创建一个接口并在任何需要它的 DTO 中使用缓存键 getter 函数实现它。

一种绝对有效的务实方法。