我构建了一个控制台应用程序,并尝试测试我的应用程序是否按预期工作。
我创建了 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();
}
}
}
}
如果您想使用Object
并且并非所有成员都是静态的,您需要使用类的实例来引用非静态成员变量。
Change:
Test_api.getQualWeight(ConStr, bin_Num, lblResults);
To:
Test_api.getQualWeight(Test_api.ConStr, Test_api.bin_Num, Test_api.lblResults);
Because ConStr
, bin_Num
, and lblResults
are instance变量它们必须是类实例的引用 - 在这种情况下Test_api
.
或者,您可以通过更改它们的声明来将这些值移动到全局静态范围中:
String ConStr = "SERVER=myservername; Database=mydb; UID=mylogin; PWD=mypassword;encrypt=no;enlist=false";
String bin_Num = "201284-11-000";
Label lblResults;
To this:
static String ConStr = "SERVER=myservername; Database=mydb; UID=mylogin; PWD=mypassword;encrypt=no;enlist=false";
static String bin_Num = "201284-11-000";
static Label lblResults;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)