2013-02-28 82 views
2

我似乎无法通过其他类的公共属性访问我的私有成员变量。我试图通过学生类在StudentList中实例化一些Student对象。我已经做过,但不能为我的生活记住或找到任何有用的东西。我对编程比较陌生,所以对我来说很简单。通过公共属性访问私有变量

学生类代码

public partial class Student : Page 
{ 
    public int StudentID { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public double CurrentSemesterHours { get; set; } 
    public DateTime UniversityStartDate { get; set; } 
    public string Major { get; set; } 
    public string FullName 
    { 
     get { return FirstName + " " + LastName; } 
    } 

    new DateTime TwoYearsAgo = DateTime.Now.AddMonths(-24); 

    public Boolean InStateEligable 
    { 
     get 
     { 
      if (UniversityStartDate < TwoYearsAgo) // at first glance this looks to be wrong but when comparing DateTimes it works correctly 
      { 
       return true; 
      } 
      else { return false; } 
     } 
    } 
    public decimal CalculateTuition() 
    { 
     double tuitionRate; 
     if (InStateEligable == true) 
     { 
      tuitionRate = 2000; 
     } 
     else 
     { 
      tuitionRate = 6000; 
     } 
     decimal tuition = Convert.ToDecimal(tuitionRate * CurrentSemesterHours); 
     return tuition; 
    } 

    public Student(int studentID, string firstName, string lastName, double currentSemesterHours, DateTime universityStartDate, string major) 
    { 
      StudentID = studentID; 
      FirstName = firstName; 
      LastName = lastName; 
      CurrentSemesterHours = currentSemesterHours; 
      UniversityStartDate = universityStartDate; 
      Major = major; 
     } 
    } 

StudentList类代码,现在基本上是空白。我一直在试图让intellisense访问我的其他课程,但没有运气到目前为止。我必须错过简单的东西。

public partial class StudentList : Page 
{ 
}  
+0

你有你的班级的实例访问? – 2013-02-28 04:04:09

+0

你想从StudentList访问学生? – 2013-02-28 04:04:46

+0

@ cuong le,是 – Milne 2013-02-28 04:05:39

回答

0

我找到了简单的解决方案。我试图从另一个页面访问后面的代码,正如你们许多人指出的那样,代码不会很好。通过将代码移入它自己的App_Code文件夹中的c#类,它可以被任何东西访问。谢谢您的帮助!

2

在这里的要点是Web应用程序是无状态应用,所以每个网页的寿命是每个请求的使用寿命。

在你的代码StudentStudentList是网页,所以从StudentList因为它没有再活下去了,你不能访问的Student实例。

因此,请考虑使用Session在页面之间传输数据。

+0

我正在寻找这样的事情... 学生学生=新的学生(StudentID,名字,姓氏,CurrentSemesterHours,UniversityStartDate,专业); – Milne 2013-02-28 04:15:18

+0

你说得对。通过将代码移入它自己的App_Code文件夹中的c#类,它可以被任何东西访问。谢谢您的帮助! – Milne 2013-03-05 15:47:18

3

首先,要回答你的问题:

“我似乎无法通过他们的 公共属性从不同的类来访问我的私有成员变量...”

是恰好为什么他们被称为私人。私人成员只能在声明它们的类中访问,并且必须使用公共属性才能从其他类访问。

现在一些建议:

1)避免使用同一个班的背后准则和领域模型类。我强烈建议您仅使用属性/业务方法创建一个单独的“学生”类,并将代码作为单独的“StudentPage”类保留。这使得您的代码更易于使用,因为不同的关注点是分开的(视图逻辑x业务逻辑),并且因为每个类都应具有不同的生命周期。

2)替代:

private int StudentID; 
public int studentID 
{ 
    get 
    { 
     return StudentID; 
    } 
    set 
    { 
     StudentID = value; 
    } 
} 

...你可以写自动属性

public int StudentId { get; set; } 
+0

伟大的建议,谢谢。 – Milne 2013-02-28 04:26:48

+0

我没有对自动属性的原因是因为我需要证明我可以通过公共属性访问私有变量。感谢关于将我的代码分离到n层体系结构的提示。它帮助我记住,我需要将我的代码移到App_Code文件夹中的自己的类中,以便我可以从任何地方访问它。谢谢! – Milne 2013-03-05 15:49:45