如何从C#中的函数检索返回的值 [英] How to retrieve a returned value from a function in C#

查看:259
本文介绍了如何从C#中的函数检索返回的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中从函数中检索值时遇到一些问题.

I got some problems in retrieving a values from a function here''s my code.

public int _countContacts(int count)
        {
            string query = @"select count(Contact ID) as count from Contacts";

            dt = _result(query);

            for (int x = 0; x < dt.Rows.Count; x++)
            {
                count = Convert.ToInt16(dt.Rows[x]["count"].ToString());
            }

            return count;
        }



这是我的其他形式的代码



And here my code in other form

private void btnRefresh_Click(object sender, EventArgs e)
        {
            //this is the wrong part
            label1.Text = func._countContacts();
        }

推荐答案

似乎您的函数定义没有意义.您应该尝试仅使用返回整数,而不使用以下参数:
It seems your function definition does not make sense. You should try to use only the return integer, not the parameter as:
public int _countContacts()
{
  int count = 0;
  string query = @"select count(Contact ID) as count from Contacts";

  dt = _result(query);
  
  for (int x = 0; x < dt.Rows.Count; x++)
  {
    count = Convert.ToInt16(dt.Rows[x]["count"].ToString());
  }
 
  return count;
}


我在您的代码中注意到的另一件事可能是错误(或者可能是正确的,并且我没有真正理解您的算法):在行数= Convert.ToInt16 ...中,您正在覆盖count的值数据表中的每一行.这是通缉犯吗?更好的代码可能是这样的:


One other thing I noticed in your code that may be an error (or it may be correct and I don''t truly understand your algorithm): In the line count = Convert.ToInt16... you are overwriting the value of count for every row in your data table. Is this wanted? Better code may be this:

for (int x = 0; x < dt.Rows.Count; x++)
{
  count += Convert.ToInt16(dt.Rows[x]["count"].ToString());
}


第一件事是您不需要在函数中提供参数,可以像在解决方案1中给出的那样在函数内部声明变量.您的函数正在返回整数值,因此您需要在button_Click上编写以下代码:
First thing is that you don''t need to provide parameter in function, you can declare variable inside function as it has given in solution 1. Second thing is that your function is returning integer value so you need to write following code on button_Click:
int i = func._countContacts();
label1.Text = i.ToString()



祝你好运.



Good luck.


这篇关于如何从C#中的函数检索返回的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆