简体   繁体   English

实施静态方法的最佳实践

[英]Best practice to implement static Method

I am trying to implement a static function in my Product class to "Get" products. 我正在尝试在我的产品类中实现“获取”产品的静态功能。

The outcome I got to work is to nest a Get subclass like this: 我要做的结果是嵌套一个Get子类,如下所示:

Product.Get.ByName("Cool Product")

But I am feeling a subclass ist not the best practice for this. 但是我感觉这不是最佳实践。

I would like to accomplish it like this what i think would be right implementation: 我想像这样实现它,我认为是正确的实现:

Product.Get().ByName(x => x.Name = "Cool Product");

How could I create this kind of sub sub method(is this even the right word?)? 我该如何创建这种子子方法(这甚至是正确的词吗?)?

If you want to add . 如果要添加. after get, you will need a subclass however you can make this subclass itself static: 获取后,您将需要一个子类,但是您可以将此子类本身设置为静态:

class Product
{
     public static class Get
     {
          public static Product ByName()
          {
                //some code to return a product (or may be products)
          }
     }
}

Now it can be accessed like: 现在可以像这样访问它:

Product.Get.ByName();

Live Demo 现场演示

Why do you need a Get class, is this simpler: 为什么您需要Get类,这很简单:

    public class Product
    {
        public static Product GetByName()
        {
            //some code to return a product (or maybe products)
        }
    }

Usage: Product.GetByName(); 用法: Product.GetByName();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM