简体   繁体   中英

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:

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:

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

Usage: Product.GetByName();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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