C# 从方法中获取大量数据的正确方法

C# 从方法中获取大量数据的正确方法,c#,model-view-controller,controller,out,C#,Model View Controller,Controller,Out,在MVC项目中,在我的控制器中,我希望获取视图中使用的数据。 假设我想要检索一个列表和一个int 我的控制器的方法声明与此类似 void GetFooData(int id, out List<string> listData, out int aValue); void GetFooData(int-id,out-List-listData,out-int-aValue); 在我使用的视图中: List<string> data; int value; contro

在MVC项目中,在我的控制器中,我希望获取视图中使用的数据。 假设我想要检索一个
列表
和一个
int

我的控制器的方法声明与此类似

void GetFooData(int id, out List<string> listData, out int aValue);
void GetFooData(int-id,out-List-listData,out-int-aValue);
在我使用的视图中:

List<string> data;
int value;
controller.GetFooData(myId, data, value);
列表数据;
int值;
controller.GetFooData(myId、数据、值);

我不喜欢这种方法。如何在不使用数据包装类的情况下以更美观的方式检索数据?

在.NET 4.0中,您可以使用元组,尽管这并没有多大改进

Tuple<List<String>, int> GetFooData(int id) {
    ...
    return Tuple.Create(list, intVal);
}

尽管您没有正确使用MVC模式,但一般来说,有很多方法可以从一个方法返回多个内容。通常为以下情况之一:

  • 使用
    out
    参数(如上所述)
  • 返回一个
    元组
    ,以保存多个项
  • 定义并返回包装器
    ,以在其属性中保存多个项(这通常是“最佳实践”)
  • 返回
    动态
    和/或
    扩展对象

可能还有更多我现在想不出来的…

您应该创建一个值对象来保存要返回的数据。我有一个程序员同事,他说“我们的参数是为年轻人和大学生准备的”。我无意冒犯大学生和孩子们,但我倾向于同意这种看法。。。我从不使用out参数

解决手头问题的最干净方法如下:

public class FooData
{
    public List<string> Strings { get; set; }
    public int MyInt { get; set; }
}

public FooData GetFooData(int id)
{
    var fooStrings = _stringRepository.GetFooStrings(id); 
    //or wherever you're getting your data from

    return new FooData
                {
                    Strings = fooStrings,
                    MyInt = id, //or whatever the int prop is supposed to be
                };
}
public ViewResult SomeViewWithFooData(int id)
{
    var fooStrings = _stringRepository.GetFooStrings(id); 
        //or wherever you're getting your data from

    var fooData = new FooData
                    {
                        Strings = fooStrings,
                        MyInt = id, //or whatever the int prop is supposed to be
                    };

    return new View(fooData);  
}
然后,您可以拥有一个名为
SomeViewWithFooData
的视图,该视图继承自
System.Web.Mvc.ViewPage
。在视图内部,只需调用
Model
即可获取数据。此时,
Model
属于FooData类型

是从控制器操作传递到视图的int


是您的字符串列表。

您的问题意味着您正在从视图直接调用控制器…?是的。但一般来说,这只是一种从方法调用中检索多个值的方法。您可能应该阅读更多有关MVC如何工作的信息。控制器应返回带有视图模型数据的
ViewResult
,然后视图访问模型。视图不应该直接访问控制器。但是,在一般情况下,您必须使用out参数或包装类。
public ViewResult SomeViewWithFooData(int id)
{
    var fooStrings = _stringRepository.GetFooStrings(id); 
        //or wherever you're getting your data from

    var fooData = new FooData
                    {
                        Strings = fooStrings,
                        MyInt = id, //or whatever the int prop is supposed to be
                    };

    return new View(fooData);  
}