【问题标题】:Non-static error, can't find reason非静态错误,找不到原因
【发布时间】:2012-02-29 02:52:08
【问题描述】:

我收到“非静态字段、方法或属性 Skirmer_Final.Nyhed.FK_Nyhed_ID.get 需要对象引用”错误。而且我不知道出了什么问题。

我的代码

public class Nyhed
{
    public int FK_Status_ID { get; set; }
    public int FK_Nyhed_ID { get; set; }

    public static List<Nyhed> GetByStatus(int ID, SqlConnection connection)
    {
        List<Nyhed> result = new List<Nyhed>();

        using (var command = new SqlCommand("Select FK_Nyhed_ID from Status_Kan_Se_Nyhed where FK_Status_ID=@id"))
        {
            command.Connection = connection;

            command.Parameters.AddWithValue("id", ID);

            SqlDataReader reader = command.ExecuteReader();
            try
            {
                while (reader.Read())
                {
                    Nyhed StatusKanSeNyhed = new Nyhed();
                    StatusKanSeNyhed.FK_Status_ID = ID;
                    StatusKanSeNyhed.FK_Nyhed_ID = reader.GetInt32(0);
                    result.Add(StatusKanSeNyhed);
                }
            }
            finally
            {
                reader.Close();
            }
            foreach (Nyhed N in result)
            {
                N.status = Status.GetByID(FK_Status_ID, connection);
                N.nyhed = Nyhed.GetByID(FK_Nyhed_ID, connection);
            }
        }
        return result;
    }
}

你能看到错误吗?

【问题讨论】:

    标签: c# foreach while-loop


    【解决方案1】:

    FK_Nyhed_ID 是一个属性。因此,您需要通过对象引用它。我猜问题出在这里:

    foreach (Nyhed N in result) {
        N.status = Status.GetByID(FK_Status_ID, connection);
        N.nyhed = Nyhed.GetByID(FK_Nyhed_ID, connection);
    }
    

    您之前在StatusKanSeNyhed 实例上引用了FK_Nyhed_ID,所以我猜您会想在下面引用N.FK_Nyhed_ID

    foreach (Nyhed N in result) {
        N.status = Status.GetByID(FK_Status_ID, connection);
        N.nyhed = Nyhed.GetByID(N.FK_Nyhed_ID, connection);  //<----- added object reference
    }
    

    【讨论】:

      【解决方案2】:

      我猜你想写的

              foreach (Nyhed N in result)
              {
                  N.status = Status.GetByID(N.FK_Status_ID, connection);
                  N.nyhed = Nyhed.GetByID(N.FK_Nyhed_ID, connection);
              }
      

      并添加缺少的N.

      【讨论】:

      • 我怎么错过了。现在感觉自己像个傻瓜
      【解决方案3】:

      FK_Status_ID 是一个实例属性,因此无法从静态方法访问。 您可以将其设为静态或将您的方法更改为实例方法。

      【讨论】:

        【解决方案4】:

        问题出在这里:

        foreach (Nyhed N in result)
                {
                    N.status = Status.GetByID(FK_Status_ID, connection);
                    N.nyhed = Nyhed.GetByID(FK_Nyhed_ID, connection);
                }
        

        您正在尝试读取公共成员 FK_Status_ID,它只能通过对象实例访问。

        【讨论】:

          猜你喜欢
          • 2020-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-08
          • 2019-10-02
          • 1970-01-01
          • 2014-06-22
          相关资源
          最近更新 更多