[英]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都必须有一个key,并且每个Key都是由它自己的属性生成的。
有人可以给我一些建议吗?
在这里,我们必须务实地思考。 在这种情况下,缓存键 getter 函数的实现不是真正的业务逻辑。
我的建议是,创建一个接口并在任何需要它的 DTO 中使用缓存键 getter 函数实现它。
务实方面的绝对有效方法。
你不应该改变 DTO 的既定目的(正如@GlennvanAcker 所说,DTO 没有逻辑)。
但是,我们可以给它一个扩展方法……这是我的建议。
public static class ProductExtensions
{
public static string CacheKey(this Product product)
{
return product.Type + "_" + product.Name;
}
}
@HansKesting 指出,我没有展示如何为除 Product 以外的其他类进行这项工作...
这将需要我们扩展基类或接口。 如果这个方法要应用于多个类; 编译器需要知道该类具有所需的属性(类型和名称):
例如
// 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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.