对象引用未设置为对象的实例(属性)

时间:2013-12-09 08:37:47

标签: c# wcf nullreferenceexception

我在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”; 我在使用之前初始化了对象。 但没有得到错误的地方。

2 个答案:

答案 0 :(得分:0)

我不知道为什么你需要一个数组,但你必须在分配值之前将其初始化。您还必须说明数组大小。我假设DBStatus是一个整数。您还应该初始化DbInstanceAssetName属性。

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;