通过公共属性访问私有变量
问题描述:
我似乎无法通过其他类的公共属性访问我的私有成员变量。我试图通过学生类在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
{
}
答
我找到了简单的解决方案。我试图从另一个页面访问后面的代码,正如你们许多人指出的那样,代码不会很好。通过将代码移入它自己的App_Code文件夹中的c#类,它可以被任何东西访问。谢谢您的帮助!
答
在这里的要点是Web应用程序是无状态应用,所以每个网页的寿命是每个请求的使用寿命。
在你的代码Student
和StudentList
是网页,所以从StudentList
因为它没有再活下去了,你不能访问的Student
实例。
因此,请考虑使用Session
在页面之间传输数据。
答
首先,要回答你的问题:
“我似乎无法通过他们的 公共属性从不同的类来访问我的私有成员变量...”
是恰好为什么他们被称为私人。私人成员只能在声明它们的类中访问,并且必须使用公共属性才能从其他类访问。
现在一些建议:
1)避免使用同一个班的背后准则和领域模型类。我强烈建议您仅使用属性/业务方法创建一个单独的“学生”类,并将代码作为单独的“StudentPage”类保留。这使得您的代码更易于使用,因为不同的关注点是分开的(视图逻辑x业务逻辑),并且因为每个类都应具有不同的生命周期。
2)替代:
private int StudentID;
public int studentID
{
get
{
return StudentID;
}
set
{
StudentID = value;
}
}
...你可以写自动属性:
public int StudentId { get; set; }
你有你的班级的实例访问? – 2013-02-28 04:04:09
你想从StudentList访问学生? – 2013-02-28 04:04:46
@ cuong le,是 – Milne 2013-02-28 04:05:39