简体   繁体   English

使用方法的命名可选参数

[英]Used Named Optional Parameters for Method

I have a method where I have several optional boolean parameters, different properties of an object will be given a value based on which parameters are true. 我有一个方法,我有几个可选的布尔参数,对象的不同属性将根据哪些参数为真给出一个值。

Here is the method for context: 这是上下文的方法:

public static AutoPatientLookup InitializeTestPatientInfo(bool SSN = false, bool PatientNumber = false, bool Gender = false)
{
    AutoPatientLookup TestAPIParameters = new AutoPatientLookup();
    TestAPIParameters.FirstName = "First";
    TestAPIParameters.LastName = "Last";
    TestAPIParameters.DOB = "4/9/1953";
    TestAPIParameters.PracticeID = 11071;

    if (SSN)
    {
        TestAPIParameters.SSN = 000010281;
    }
    if (PatientNumber)
    {
        TestAPIParameters.PatientNumber = 458;
    }
    if (Gender)
    {
        TestAPIParameters.Gender = "F";
    }

    return TestAPIParameters;
}

However, sometimes I want the second or third boolean parameter to be true but I'm unable to designate that as the parameter I want to switch without explicitly stating true or false for the preceding parameters. 但是,有时我希望第二个或第三个布尔参数为true,但是我无法将其指定为我想切换的参数,而不会为前面的参数明确说明true或false。

This if I want to initialize an AutoPatientLookup object that has a value for its gender property, I would have to call it like this: 这个如果我想初始化一个具有性别属性值的AutoPatientLookup对象,我必须这样调用它:

InitializeTestPatientInfo(false,false,true);

I tried something along the lines of 我尝试了一些类似的东西

InitializeTestPatientInfo(Gender = true);

and

InitializeTestPatientInfo(bool Gender = true);

but nothing seems to work. 但似乎没什么用。 Is there a correct syntax for accomplishing for what I'm attempting? 是否有正确的语法来完成我正在尝试的内容? Even though the initialization syntax isn't very inconvenient when there are only three boolean parameters this could be more applicable if there are dozens. 即使只有三个布尔参数,初始化语法也不是很不方便,如果有几十个,这可能更适用。

您要使用的语法是:

InitializeTestPatientInfo(Gender: true);

尝试

InitializeTestPatientInfo(Gender: true);

You can name your parameter that you are assigning: 您可以为要分配的参数命名:

Do this instead 这样做

InitializeTestPatientInfo(Gender: true);

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

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