【问题标题】:Observable Collection C# unable to accessObservable Collection C# 无法访问
【发布时间】:2014-07-10 23:18:04
【问题描述】:

两个愚蠢的疑问:

  1. 我无法在我引用的另一个类中访问属性Students。请告诉我为什么我无法引用或调用它?

  2. 除了使用ref 关键字外,我不能在类级别声明一个变量并在该类内部的方法中访问它吗?假设我有一个名为 Display 的方法,其返回类型为 IEnumerable<Student>,在其中,我想调用并返回 StudentsListDetails

我的班级是这样的:

public class Service
{
    private ObservableCollection<Student> studentsList;

    public ObservableCollection<Student> StudentsListDetails;

    public StudentEntities StudentEntities { get; set; }

    public ObservableCollection<Student> Students
    {
        get
        {
            if (studentsList == null && StudentEntities != null)
            {
                StudentEntities.Set<Student>().Load();
                studentsList = StudentEntities.Set<Student>().Local;
                StudentsListDetails = studentsList;
            }

            return studentsList;
        }
    } 
}

【问题讨论】:

  • 很难弄清楚你在这里实际问的是什么。你能让你的问题更不稳定吗?
  • 请更新您的问题以明确问题。
  • @awexfwex:好的,我想在返回 IEnumerable 的方法中访问 StudentsListDetails。第二 - 我应该能够从其他班级访问“学生”属性。
  • @loop:我更新了上面的评论,请帮忙?

标签: c# .net wpf winforms oop


【解决方案1】:

我不确定您的问题,但我认为首先它会对您有所帮助:-

1-> 您必须通过使用其他类中的服务类的对象来访问学生属性。像这样

    Service objService = new Service();
    var lst = objService.Students; 

2->你能把你想要使用“StudentsListDetails”的方法和你正在编写这个方法的类放在里面吗?

你更新它,如果可以的话,我会尽力帮助你。

【讨论】:

  • 非常感谢,这对我帮助很大。自从有一段时间没有编码以来,我似乎忘记了很多事情。
【解决方案2】:

广告。 1 由于Students在上面的代码中不是静态的,你首先必须创建一个Service类的实例,然后你可以访问Students属性

Service serv = new Service();
ObservableCollection<Student> students = serv.Students;

如果不希望有一个 Service 实例,您希望将 Student 属性(以及代码中使用的所有字段/方法/属性)设为静态。然后你像这样访问它:

ObservableCollection<Student> students = Service.Students;

广告。 2. 如果方法和变量都在同一个类中,则不需要 ref/out 关键字。您可以直接访问和修改它(除非修改已被 const 或 readonly 等关键字明确禁止)。

【讨论】:

  • 谢谢,虽然同一个类,但恐怕我没有得到函数外变量的智能感知。哎呀,真讨厌
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 2017-06-19
  • 1970-01-01
  • 2014-04-28
  • 2012-03-04
  • 1970-01-01
  • 2021-12-25
相关资源
最近更新 更多