首页 > 解决方案 > 常用方法高效处理

问题描述

我正在研究一种通用方法,它(现在)做同样的事情,但将来可能最终需要扩展。

说这个方法是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()移到一个通用的类文件中,并HomePageProductsPage.

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();  
    }

谢谢大家。

标签: c#oop

解决方案


继承并不总是答案。有时像下面这样的简单助手可以做到

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();
    }
} 

推荐阅读