抱歉这个愚蠢的问题。我刚刚开始进行C#编程。我现在已经研究了好几个小时,并在这里阅读我能做的。这似乎很常见,我只是不明白为什么它不起作用。我想在父方法中声明一个变量并更改子类中的值。如果这不是这样做的方法,我怎样才能创建返回有用数据的方法(甚至是循环或while循环)?
示例1:
static void Main(string[] args)
{
int rowID;
for (int i = 1; i < 500; i++ )
{
rowID = i;
}
Console.WriteLine(rowID);
}
示例2:
private void SendButtonClicked(object sender, System.EventArgs e)
{
// finds the first row that has not been sent
int rowID = GetMessageRow();
//then process the row and figure out what stored procedure to run
RunStoredProcedure(rowID);
}
public int GetMessageRow()
// finds the first row that has not been sent
{
int rowID;
// skipping some code
while (drGetMessageRow.Read())
{
// while loop does not understand the variable and errors
rowID = drGetMessageRow.GetInt32(0);
MessageBox.Show("1: RowID is " + rowID.ToString());
}
}
答案 0 :(得分:2)
使用return
关键字从方法返回值。此关键字退出该方法。例如:
return rowID;
答案 1 :(得分:1)
您需要返回值。例如,在while
中GetMessageRow
循环后,您应该这样做
return rowID
答案 2 :(得分:1)
您的GetMessageRow方法需要返回rowID。这是允许rowID(这是一个不同的变量)在SendButtonClicked方法中设置其值的原因。
public int GetMessageRow()
// finds the first row that has not been sent
{
int rowID;
// skipping some code
while (drGetMessageRow.Read())
{
// while loop does not understand the variable and errors
rowID = drGetMessageRow.GetInt32(0);
MessageBox.Show("1: RowID is " + rowID.ToString());
}
return rowID;
}
答案 3 :(得分:1)
要更改您开始进入ref
领域的方法之间的值<(意味着值本身) - 但我建议DON&#39; T这样做......然而。
返回一个有用的值return
。特别是循环的一个问题是它们可能不会迭代一次,所以就“明确赋值”而言,它们可能不会迭代。您经常需要在循环外指定默认值。
如果您没有进入循环,或使用throw
或.First()
等LINQ方法,则另一个选择是.Single()
。
答案 4 :(得分:1)
假设您要为GetMessageRow
方法返回的单个rowId运行存储过程,您需要从方法返回值:
public int GetMessageRow()
// finds the first row that has not been sent
{
int rowID;
// skipping some code
while (drGetMessageRow.Read())
{
// while loop does not understand the variable and errors
rowID = drGetMessageRow.GetInt32(0);
MessageBox.Show("1: RowID is " + rowID.ToString());
}
return rowID;
}
如果要调用每行的存储过程,而不是在循环内调用RunStoredProcedure
,则传递当前的rowId:
public void ProcessMessageRows()
// finds the first row that has not been sent
{
// skipping some code
while (drGetMessageRow.Read())
{
// while loop does not understand the variable and errors
int rowID = drGetMessageRow.GetInt32(0);
MessageBox.Show("1: RowID is " + rowID.ToString());
RunStoredProcedure(rowId);
}
}
答案 5 :(得分:0)
我发现我可以将所有内容都放入类似的课程中。
class Sproc
{
public static int rowID = 0;
public int GetMessageRow(); ...
public void RunStoredProcedure(int rowID)...
}
....然后我可以打电话如下。
SProc s;
s = new SProc();
// finds the first row that has not been sent
int rowID = s.GetMessageRow();
//then process the row and figure out what stored procedure to run - this could be (should be) also in the config.
s.RunStoredProcedure(rowID);