我在WCF接口中有一个属性
string DBStatus(string Instance,string Asset,string Type);
[DataContract]
public class DatabaseDetails
{
[DataMember]
public string[] DBStatus { get; set; }
}
在课堂上实施以下方法
public string DBStatus(string Instance, string Asset, string Type)
{
DatabaseDetails DbDetails = new DatabaseDetails();
int DBStatus = 0;
using (SqlConnection SqlConn = new SqlConnection())
{
try
{
//SqlConn.ConnectionString = "Data Source=" + ServerName + "Initial Catalog=" + DBName + "User id=" + UserId + "Password=" + Pwd;
SqlConn.ConnectionString = "server=" + ServerName + ";database=" + DBName + ";UID=" + UserId + ";PWD=" + Pwd;
SqlConn.Open();
DbDetails.DBStatus[DBStatus] = "Online";
DbDetails.DbInstance[DBStatus] = Instance;
DbDetails.AssetName[DBStatus] = Asset;
DBStatus++;
//json = "Online";
}
catch (Exception e)
{
json = "Offline";
}
}
}
获取对象引用错误@Line:DbDetails.DBStatus [DBStatus] =“Online”; 我在使用之前初始化了对象。 但没有得到错误的地方。
答案 0 :(得分:0)
我不知道为什么你需要一个数组,但你必须在分配值之前将其初始化。您还必须说明数组大小。我假设DBStatus是一个整数。您还应该初始化DbInstance
和AssetName
属性。
public string DBStatus(string Instance, string Asset, string Type)
{
DatabaseDetails DbDetails = new DatabaseDetails
{
DBStatus = new string[DBStatus + 1]
//initialize DbInstance and AssetName too
};
using (SqlConnection SqlConn = new SqlConnection())
{
try
{
//SqlConn.ConnectionString = "Data Source=" + ServerName + "Initial Catalog=" + DBName + "User id=" + UserId + "Password=" + Pwd;
SqlConn.ConnectionString = "server=" +ServerName+ ";database=" +DBName+ ";UID=" +UserId+ ";PWD="+Pwd ;
SqlConn.Open();
DbDetails.DBStatus[DBStatus] = "Online";
DbDetails.DbInstance[DBStatus] = Instance;
DbDetails.AssetName[DBStatus] = Asset;
DBStatus++;
//json = "Online";
}
catch (Exception e)
{
json = "Offline";
}
}
}
答案 1 :(得分:0)
虽然您的代码非常混乱,但您可能需要初始化字符串数组。
DbDetails.DBStatus = new string[3];
DbDetails.DBStatus[DBStatus] = "Online";
DbDetails.DbInstance[DBStatus] = Instance;
DbDetails.AssetName[DBStatus] = Asset;