我似乎无法通过不同类的公共(public)属性访问我的私有(private)成员变量。我正在尝试通过 Student 类实例化 StudentList
中的一些 Student
对象。我以前做过,但我一生都记不起或找不到任何有效的东西。我对编程还比较陌生,所以对我来说要轻松一些。
学生类(class)代码
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 类代码现在基本上是空白的。我一直在摆弄它,试图让智能感知访问我的其他类(class),但到目前为止还没有运气。我一定错过了一些简单的东西。
public partial class StudentList : Page
{
}
最佳答案
首先回答你的问题:
"I can't seem to access my private member variables through their public properties from a different class..."
这正是它们被称为私有(private)的原因。私有(private)成员只能在声明它们的类中访问,并且必须使用公共(public)属性才能从其他类访问。
现在,一些建议:
1) 避免使用与代码隐藏和域模型类相同的类。我强烈建议您仅使用属性/业务方法创建一个单独的“Student”类,并将代码保留为单独的“StudentPage”类。这使得您的代码更易于使用,因为不同的关注点是分开的( View 逻辑 x 业务逻辑),并且每个类都应该有不同的生命周期。
2)而不是:
private int StudentID;
public int studentID
{
get
{
return StudentID;
}
set
{
StudentID = value;
}
}
...您可以编写自动属性:
public int StudentId { get; set; }
关于c# - 通过公共(public)属性访问私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15127257/