返回一个对象和一个列表

时间:2016-05-05 07:06:56

标签: c# .net json list return

在方法

    计算
  1. 计数

  2. 也形成了一个列表

  3. 我需要将此计数与c#中的列表一起返回。有关如何退货的任何建议吗?

4 个答案:

答案 0 :(得分:2)

您应该avoid using out and ref parameters

我建议创建一个表示输出结果的类型。

public DoSomethingResult DoSomething()
{
    var result = new DoSomethingResult();
    //....
    result.Data = GenerateList();
    result.Count = CalculateCount();
    return result;
}

public class DoSomethingResult
{
    public List<YourType> Data { get; set; }
    public int Count { get; set; }
}

FxCop rule for out parametes.

答案 1 :(得分:0)

2个选项

  1. 使用param进行计数,返回类型为List
  2. 使用包含CountList
  3. 的元组或自定义类

    示例代码:

     public List<Class1> GetData(out int Count)
     { 
       //... 
        //Your Logic with returning list
     }
    

    选项2:

    public CustomClass DoSomething()
    {
        var data = new CustomClass();
        //....
        data.Data = list;
        data.Count = list.Count();
        return data;
    }
    public class CustomClass
    {
        public List<Class1> Data { get; set; }
        public int Count { get; set; }
    }
    

答案 2 :(得分:0)

您只需返回List并在调用方法中获取Count即可。你并不真的要求两者都归还。

还有兴趣吗?多种选择。

使用out参数进行计数。

public List<something> DoSomething(out int count)
{
    ....
    count = list.Count();
    return list; 
}

在评论中使用Tuple

public Tuple<List<something>, int> DoSomething()
{
    ....
    return new Tuple<List<something>, int>(list1, count); 
}

答案 3 :(得分:0)

您应该在C#中使用out关键字。

MSDN说明。 &#34;当您希望方法返回多个值时,声明out方法很有用。这使得方法可以选择性地返回值。&#34;

Here是MSDN文档。

以下是一个例子:

public List<YourType> SomeMethodName(out int count)
{
    //Your calculation here
}
相关问题