代码之家  ›  专栏  ›  技术社区  ›  Ortund

重载没有参数的方法

  •  1
  • Ortund  · 技术社区  · 7 年前

    第一个将页面上的ASP GridView控件与所选数据绑定:

    // Bind the GridView with the data.
    private void LoadArticles()
    {
        List<ListArticleViewModel> model = new List<ListArticleViewModel>();
    
        // Query the database and get the data.
    
        GridView1.DataSource = model;
        GridView1.DataBind();
    }
    

    第二种实现是返回与可枚举数据相同的列表:

    private IEnumerable<ListArticleViewModel> LoadArticles()
    {
        List<ListArticleViewModel> model = new List<ListArticleViewModel>();
    
        // Query the database and get the data.
    
        return model.AsEnumerable();
    }
    

    显然,重载在这里不起作用,因为签名不区分返回类型。

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods

    出于方法重载的目的,方法的返回类型不是方法签名的一部分。

    这让我有点进退两难,因为我实际上不需要参数,所以我该如何重载它并使其工作呢?

    我应该为该方法使用不同的名称吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Flater    7 年前

    从技术角度来看,重载与应用程序的工作方式无关。没有真正的理由希望几个不同的方法具有相同的名称,唯一的例外是 开发者可读性

    您可以命名这些方法 Superman() Batman() ,并且它不会改变应用程序的工作方式。就编译器而言,名称无关紧要。

    因此,您的问题的简短答案是: 不要给那些方法取相同的名字!

        2
  •  0
  •   Bhuban Shrestha    7 年前

    但是你在你的方法中做了两件事

    private void LoadArticles()
    {
       //Load data
        List<ListArticleViewModel> model = new List<ListArticleViewModel>();
    
        //Bind loaded Data
        GridView1.DataSource = model;
        GridView1.DataBind();
    }
    

    很明显,在一种方法中加载和绑定要做两件事。哦,不建议这样做。相反,您应该只从该方法返回数据

    public IEnumerable<ListArticleViewModel> LoadArticles()
    {
        List<ListArticleViewModel> model = new List<ListArticleViewModel>();
    
        // Query the database and get the data.
    
        return model.AsEnumerable();
    }
    

    现在,您可以在任何地方使用上述公共方法。(如果需要,可以更改访问修饰符)

    var dataSource = new Article().LoadArticles();
    GridView1.DataSource = dataSource;
    GridView1.DataBind();
    

    如果您不喜欢这种方法,那么也不能使用返回类型相同且两种方法都没有输入参数的方法重载方法来解决问题。相反,您可以重命名其中一个方法,然后就可以开始了。