【问题标题】:Using Dictionary Parameters as Optional Arguments when Calling Method调用方法时使用字典参数作为可选参数
【发布时间】:2018-02-22 21:41:12
【问题描述】:

我目前正在尝试在调用方法时使用字典值来命名可选参数。我不确定这对 c# 是否可行,但我对使用动态 SQL 的查询做了类似的事情。

string[] dobArrayKey = {"dob: "};
string[] dobArrayValue = {txtDob.Text};
string[] ptntNumArrayKey = { "PatientID: " };
string[] ptntNumArrayValue = { txtOfficeMR.Text};
string[] nameArrayKey = { "FirstName: ", "LastName: " };
string[] nameArrayValue = { txtFirstname.Text, txtLastname.Text };

List<List<string>> searchResults = new List<List<string>>();


Dictionary<string[], string[]> searchCriteria = new Dictionary<string[], string[]> 
{ 
    {dobArrayKey,dobArrayValue}
    ,{ptntNumArrayKey,ptntNumArrayValue}
    ,{nameArrayKey,nameArrayValue}
};

foreach (var item in searchCriteria)
{
    if (item.Value[0] != "" && item.Value[0] != null)
    {
        searchResults.Add(new List<string>());

        for (int x = 0; x <= item.Key.Count(); x++)
        {
            string strJSON = doPatientSearch(Convert.ToInt32(au.UserID)
                , Convert.ToInt32(Session["PracticeID"]), au.SessionID, item.Key[x].ToString() : item.Value[x].ToString() );         

            PatientSearchResponse ptLi = JsonConvert.DeserializeObject<PatientSearchResponse>(json2);

            foreach (PatientList3 patient in ptLi.PatientList)
            {
                searchResults[x].Add(patient.PatientNumber);
            }

        }
    }
}

public static string doPatientSearch(int UserID, int PracticeID, string SessionID, string PatientID = null,
        ,string first = null, string last = null, string dob = null,  string social = null)
{
    //search
}

我的同事建议我通过删除所有可选参数来更改方法本身,而是通过包含所有参数的字典并在方法中处理它们。

我认为这可行,但出于好奇,我想获得一些反馈,并了解我在上述代码中尝试做的事情是否可行。

如果这是不可能的,但有另一种方法可以达到预期的结果,我很乐意看到你的建议。

提前谢谢你。

【问题讨论】:

  • 一本字典表明参数实际上可以是任何东西。相反,我会为真正的公共方法使用接口,为任何内部/受保护/私有方法使用类。 IPatientSearchCriteriaPatientSearchCriteria.
  • 搜索在物理上是如何执行的?在某些时候是否有存储过程调用?
  • @JohnWu 没有执行存储过程。这些参数用于构建 API 调用。
  • API 调用的签名是什么?最终,您传入的任何参数都需要映射到 API,对吧?
  • @JohnWu 如果我正确理解您的问题,是的。签名由从 au 对象中检索到的 userID、sessionID 和 practiceID 组成,我没有将其结构和初始化包括在问题中,因为我认为它没有密切关系。我在循环中尝试做的每次迭代是使用字典搜索条件传递不同的可选参数,然后在事后比较结果。

标签: c# optional-parameters


【解决方案1】:

传递一个表达式

由于条件是事后使用的(即通过过滤完整的结果集),您可以使用 LINQ 过滤结果。为了获得最大的灵活性,调用者可以传入 Expression 以用作每个项目的回调,以确定是否应包含它。

要获得过滤后的结果集:

public IEnumerable<Patient> FindPatients(Func<Patient,bool> criteria)
{
    return sourceData
        .Where (criteria);
}

返回单个结果:

public Patient FindPatient(Func<Patient,bool> criteria)
{
    return sourceData
        .Single(criteria);
}

criteria 表达式只是一个接受患者并返回布尔值的函数。调用者可以任意编写,或者将其作为 lambda 表达式插入。

var results = patients.FindPatients( p => p.LastName == "Doe" );

或者

var results = patients.FindPatients
(   
    p =>
    p.LastName.Contains("Doe") && 
    p.PracticeID == 12 
);

或者

    var singleResult = patients.FindPatient( p => p.UserID == 1);

如您所见,调用者可以提供所需的任何标准,并具有类型安全和早期绑定的好处。这比使用两者都没有的字典要好得多。

完整示例代码:

class Patient
{
    public int      UserID     { get; set; }
    public int      PracticeID { get; set; }
    public string   FirstName  { get; set; }
    public string   LastName   { get; set; }
    public DateTime DOB        { get; set; }
    public string   Social     { get; set; }
    public override string ToString()
    {
        return string.Format("{0} {1} {2}", UserID, FirstName, LastName);
    }
}

class PatientRepository
{
    static private readonly List<Patient> sourceData = new List<Patient>
    {
        new Patient
        {
            UserID = 1, PracticeID = 10, FirstName = "John", LastName = "Doe", DOB = DateTime.Parse("1/2/1968"), Social="123456789"
        },
        new Patient
        {
            UserID = 2, PracticeID = 10, FirstName = "Jane", LastName = "Doe", DOB = DateTime.Parse("1/2/1958"), Social="123456790"
        },
        new Patient
        {
            UserID = 3, PracticeID = 10, FirstName = "John", LastName = "Carson", DOB = DateTime.Parse("4/1/1938"), Social="123456791"
        }
    };

    public IEnumerable<Patient> FindPatients(Func<Patient,bool> criteria)
    {
        return sourceData
            .Where (criteria);
    }
    public Patient FindPatient(Func<Patient,bool> criteria)
    {
        return sourceData
            .Single(criteria);
    }
}

public class Program
{
    public static void Main()
    {
        //Get a reference to the data store
        var patients = new PatientRepository();

        Console.WriteLine("Multiple record search");
        var results = patients.FindPatients
        ( 
            p => p.LastName == "Doe" 
        );
        foreach (var p in results)
        {
            Console.WriteLine(p);
        }

        Console.WriteLine("Single record search");
        var singleResult = patients.FindPatient
        (
            p => p.UserID == 1
        );
        Console.WriteLine(singleResult);
    }
}

输出:

Multiple record search
1 John Doe
2 Jane Doe
Single record search
1 John Doe

See the working code on DotNetFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多