c# - 常用方法高效处理
问题描述
我正在研究一种通用方法,它(现在)做同样的事情,但将来可能最终需要扩展。
说这个方法是GetProducts()
在主页和产品页面中调用的。
所以我的代码如下:
class HomePage
{
public List<BaseInfo> LoadHomePage()
{
List<BaseInfo> baseInfo = new List<BaseInfo>();
baseInfo.Add(GetProducts(5));
return baseInfo;
}
public Products GetProducts(int count)
{
return apiProducts().Take(count).ToList();
}
}
然后,在另一个类文件中:
class ProductsPage
{
public List<BaseInfo> LoadProductPage()
{
List<BaseInfo> baseInfo = new List<BaseInfo>();
baseInfo.Add(GetProducts(100));
return baseInfo;
}
public Products GetProducts(int count)
{
return apiProducts().Take(count).ToList();
}
}
现在,我想把它GetProducts()
移到一个通用的类文件中,并HomePage
在ProductsPage
.
class CommonMethods
{
public Products GetProducts(int count)
{
return apiProducts().Take(count).ToList();
}
}
遗产:
class HomePage : CommonMethods
class ProductsPage: CommonMethods
但是,当我需要GetProducts
在产品页面上针对特定目的进行修改并且不想影响HomePage
时,最好的方法是什么?我想避免破坏其他页面,因为我正在更改常用方法。
我尝试了制作GetProducts()
虚拟并覆盖上的方法的想法ProductsPage
。那会奏效,但我仍在考虑这里是否有更好的方法。有没有我可以考虑的设计模式?
编辑:
我试图避免的主要问题是通过一种通用方法,当我对此进行更改时,我不想破坏主页和产品页面上的功能GetProducts()
;
例如,在主页上,我只需要 2 个数据(ID 和名称)
然后在 ProductsPage 上,我想扩展返回的数据,比如价格、数量等示例方法,但我正在寻找更好的解决方案:
public Products GetProducts(int count, string page)
{
if(page == "Home")
return apiProducts().Select(x => new Products { Id = x.id, Name = x.name, Name = x.name }).Take(count).ToList();
elseif (page == "Products")
return apiProducts().Select(x => new Products { Id = x.id, Name = x.name, Name = x.name, Price = x.price, Qty = x.qty }).Take(count).ToList();
}
谢谢大家。
解决方案
继承并不总是答案。有时像下面这样的简单助手可以做到
internal static class ProductsHelper // -- STATIC
{
// generic method that will work for all products
public static List<T> GetProducts<T>(IEnumerable<T> products, int count)
{
return products.Take(count).ToList();
}
}
推荐阅读
- python - 根据 CSV 文件中的数据在字典中创建字典
- java - 如何在从网页获取报告时修复抛出的 IllegalStateException
- ssh - Ngrok SSH 连接被远程主机关闭
- node.js - 当 props.match.params.id 返回 undefined 但 id 在 url 上可见时,如何获取 url 的 id 参数?
- c - 在 C 中使用指针数组失败
- java - springfox-swagger-ui 2.9.2 不显示 swagger-ui.html 页面返回 404
- java - 解锁企业网络中的防火墙以访问 Google 文本到语音 API 需要什么 URL?
- javascript - 如何在 NodeJS 中从文本文件中读取特殊字符
- swift - Custom InfoWindow for google maps - Unable to set y position
- python - Finding the exact name of City and Country