Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回KeyValuePair或在C#中使用out变量?_C# - Fatal编程技术网

返回KeyValuePair或在C#中使用out变量?

返回KeyValuePair或在C#中使用out变量?,c#,C#,我有一个函数需要返回两个字符串。我考虑过两种不同的方法: string first = "this is first"; string second = "this is second"; KeyValuePair<string, string> ReturnPair() { return new KeyValuePair<string, string>(first, second); } string ReturnOne(out string other) {

我有一个函数需要返回两个字符串。我考虑过两种不同的方法:

string first = "this is first";
string second = "this is second";
KeyValuePair<string, string> ReturnPair()
{
    return new KeyValuePair<string, string>(first, second);
}
string ReturnOne(out string other)
{
    other = second;
    return first;
}
string first=“这是第一个”;
string second=“这是第二个”;
KeyValuePair ReturnPair()
{
返回新的KeyValuePair(第一个、第二个);
}
字符串返回一(输出字符串其他)
{
其他=秒;
先返回;
}
我想使用KeyValuePair方法,但我觉得我误用了创建此对象的目的

我的问题是:

  • 在本例中,是否有更好的方法返回2个字符串
  • 返回KeyValuePair有什么问题吗

  • 我个人的意见是

    void ReturnTwo(out string one, out string two)
    {
      // do assignments
    }
    
    我觉得这使得返回值更加明确。

    虽然返回
    KeyValuePair
    在技术上没有问题,但从概念上讲,返回的不是“键值”对。这是一双简单的

    或者,您可以使用.NET 4.0中提供的
    元组
    ,或者同时声明


    我通常建议不要使用
    out
    参数返回元组。特别是当您使用LINQ和函数式语言构造时,使用
    out
    参数非常繁琐。

    如果数据在逻辑上属于同一类,但在逻辑上不是另一类的键,我将定义一个封装它的新类型


    如果一个是另一个的密钥,我会使用NameValuePair。

    这是我首选的方法。KeyValuePair太冗长了

    String[] ReturnPair()
    {
        return new [] { first, second };
    }
    

    有一个类似的问题,有各种各样的答案:


    从“干净代码”的角度来看,使用“out”参数返回这两个字符串是不好的。假设您没有时间重构/清理您的设计,John Kraft提出的解决方案肯定是可以接受的。

    我不喜欢多输出参数。如果第一个字符串不是真正的键,我也不喜欢使用键值对。我的建议是返回列表。这将提供灵活和稳定的签名。例如,如果您以后决定返回3或4个字符串,您只需更新方法内部的逻辑,而不必修改签名。

    我也要这么说。例如,如果您代表一个人的两个名字,那么您可以拥有一个具有FirstName和LastName属性的类。这打开了将来创建全名getter的可能性。正确,我返回的不是KeyValuePair,这就是为什么我在使用该构造时犹豫不决的原因。这是一个元组。谢谢你的想法。