【问题标题】:Method naming GetX by multiple parameters多参数命名GetX的方法
【发布时间】:2013-11-23 00:52:57
【问题描述】:

我正在设计一个工厂类,并且想知道在根据不同参数检索对象集合时,可接受的方法命名约定是什么。

例子:

从我的数据源获取所有对象(#1 无参数):

public GetAll(){...}

获取所有具有匹配名称的对象(#2 名称参数):

public GetByName(string name){..}

获取所有匹配'another property'的对象(#3 'another property'参数):

public GetByAnotherProperty(string anotherProperty){...}

现在,我遇到麻烦的地方是当我想添加一个获取两个或多个属性的 get 方法时:

获取所有具有匹配名称和“另一个属性”的对象(#4 两个参数):

我的一些尝试:

public GetByNameAndAnotherProperty(string name, string anotherProperty){...}
public GetByNameByAnotherProperty(string name, string anotherProperty){...}
public Get(string name, string anotherProperty){...}

一旦我有两个或三个以上的参数,我可以看到前两种方法变得非常麻烦。示例:

public GetByNameByPropertyXByPropertyYByPropertyZ(string name, etc.){...}

有没有更好的方法来做到这一点?如何设计一个灵活的类来接受任意数量的参数并保持命名约定简洁明了?

任何帮助都会很棒!

【问题讨论】:

    标签: c# methods overloading


    【解决方案1】:

    也许我误解了这个问题,但在我看来你正在寻找这个:

    http://msdn.microsoft.com/en-us/library/w5zay9db(v=vs.110).aspx

    public FooClass GetByProperties(params string[] list)
    

    【讨论】:

    • 谢谢。但是如何区分列表中的项目是属性 A 还是 B?
    • 你不能。如果您必须区分它们,请创建一个表示方法输入参数的类。如果您有超过 5 个输入参数,也建议使用此方法。所以,它看起来像这样: public FooClass GetByProperties(ParamClass parameters);
    • 我选择了可​​选/命名参数,以尽量减少对方法重载的需求。 Technique used.感谢您的帮助。
    猜你喜欢
    • 2022-01-17
    • 2015-02-04
    • 2012-12-04
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多