繁体   English   中英

我是否正确使用列表?

[英]Am I using Lists correctly?

在我的页面加载中,我是一次还是三次调用ReturnStuff() 如果我打电话三遍,有没有更有效的方法呢?

protected void Page_Load(object sender, EventArgs e)
{
    string thing1 = ReturnStuff(username,password)[0];
    string thing2 = ReturnStuff(username, password)[1];
    string thing3 = ReturnStuff(username, password)[2];
}

public static List<string> ReturnStuff(string foo, string bar)
{

    // Create a list to contain the attributes
    List<string> Stuff = new List<string>();

    // Some process that determines strings values based on supplied parameters

    Stuff.Add(fn);
    Stuff.Add(ln);
    Stuff.Add(em);

    return Stuff;
}

你叫了三遍。 这是一种更有效的方法:

protected void Page_Load(object sender, EventArgs e)
{
    var stuff = ReturnStuff(username,password);
    string thing1 = stuff[0];
    string thing2 = stuff[1];
    string thing3 = stuff[2];
}

但除此之外,如果您有名字,姓氏和电子邮件,我将编写一个函数,该函数返回一个由名字,姓氏和电子邮件组成的对象:

public class User
{
     public string LastName {get;set;}
     public string FirstName {get;set;}
     public string EMail {get;set;}
}

public static User GetUser(string username, string password)
{ 
    // Some process that determines strings values based on supplied parameters

    return new User() {FirstName=fn, LastName=ln, EMail=em};
}

protected void Page_Load(object sender, EventArgs e)
{
    var user = GetUser(username,password);
}

您打电话了3次。 调用一次并将结果保存到变量中,然后就可以使用该变量。

尝试这个:

var stuff = ReturnStuff(username,password);
string thing1 = stuff[0];
string thing2 = stuff[1];
string thing3 = stuff[2];

3次。 以下代码将帮助您实现。 转到Main函数,然后从那里调用func()。

class howmanytimescallingafunction
     {
        public static int i = 0;
        public List<string> fun()
        {
            List<string> list = new List<string> { "A", "B", "C" };
            i++;
            return list;
        }
        public void func()
        {
            Console.WriteLine(fun()[0]);
            Console.WriteLine(i);
            Console.WriteLine(fun()[1]);
            Console.WriteLine(i);
            Console.WriteLine(fun()[2]);
            Console.WriteLine(i);
        }
    }

您应该调用该函数一次,在本地List <>变量中获取返回的值,然后使用该变量进行访问。 像这样:

List<string> list = function-that-returns-List<string>();
list[0]; //Do whatever with list now.

暂无
暂无

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

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