我构建了一个控制台应用程序,并试图测试我的应用程序是否按预期工作。
我创建了API类的一个实例,如下面的代码所示,但我收到一个错误:
An object reference is required for the non-static field.
我已经检查了类似的问题,如this one但它看起来不同。我究竟做错了什么?如何在窗口控制台应用程序中调用非静态方法
namespace ConsoleApplication1
{
class Api
{
String ConStr = "SERVER=myservername; Database=mydb; UID=mylogin; PWD=mypassword;encrypt=no;enlist=false";
String bin_Num = "201284-11-000";
Label lblResults;
static void Main(string[] args)
{
Api Test_api = new Api();
Test_api.getQualWeight(ConStr, bin_Num, lblResults);
}
public Dictionary<String, String> getQualWeight(String sqlConStr, String inBin, Label lblResults)
{
Dictionary<String, String> qualList = new Dictionary<string, string>();
string selectSQL = "select Name,qual_weight from Qualification_type "
+ "where ID in (select Qualification_ID from Qualifications where BIN = @inBin)";
con = getConn(sqlConStr);
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("@inBin", inBin);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
qualList.Add(reader[0].ToString(), reader[1].ToString());
}
reader.Close();
return qualList;
}
catch (Exception err)
{
lblResults.Text = "error fetching qualification weight " + err.Message;
return null;
}
finally
{
con.Close();
}
}
}
}
谢谢@Matt Razza – kombo 2012-07-25 13:43:04
您的解决方案是正确的 – kombo 2012-07-25 13:45:46