在我的页面加载中,我是拨打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;
}
答案 0 :(得分:13)
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);
}
答案 1 :(得分:1)
试试这个:
var stuff = ReturnStuff(username,password);
string thing1 = stuff[0];
string thing2 = stuff[1];
string thing3 = stuff[2];
答案 2 :(得分:1)
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&lt;&gt;中获取返回值变量然后使用变量进行访问。像这样:
List<string> list = function-that-returns-List<string>();
list[0]; //Do whatever with list now.