C# 通过公共属性访问私有变量
我似乎无法通过私有成员变量的公共属性从其他类访问它们。我试图通过Student类实例化C# 通过公共属性访问私有变量,c#,asp.net,.net,private-members,C#,Asp.net,.net,Private Members,我似乎无法通过私有成员变量的公共属性从其他类访问它们。我试图通过Student类实例化StudentList中的一些Student对象。我以前做过,但我一辈子都记不住或找不到任何有用的东西。我对编程比较陌生,所以对我放松点 学生班级代码 public partial class Student : Page { public int StudentID { get; set; } public string FirstName { get; set; } public s
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;
}
}
这里的要点是web应用程序是无状态的应用程序,因此每个web页面的生存期都是每个请求的生存期 在您的代码中,
Student
和StudentList
是网页,因此从StudentList
您无法访问Student
的实例,因为它不再存在
<>请考虑使用<代码>会话>代码>页面间的数据传输。 < P>,首先回答你的问题: “我似乎无法通过私有成员变量访问它们 来自不同类的公共属性…” 这就是为什么他们被称为私人。私有成员只能在声明它们的类中访问,并且必须使用公共属性才能从其他类访问 现在,有一些建议: 1) 避免使用与代码隐藏和域模型类相同的类。我强烈建议您仅使用属性/业务方法创建一个单独的“Student”类,并将代码作为单独的“StudentPage”类保留。这使您的代码更易于使用,因为不同的关注点是分开的(视图逻辑x业务逻辑),并且这些类中的每个类都应该有不同的生存期 2) 而不是:
private int StudentID;
public int studentID
{
get
{
return StudentID;
}
set
{
StudentID = value;
}
}
。。。您可以编写自动属性:
我找到了简单的解决办法。我试图从一个页面访问另一个页面背后的代码,正如你们中的许多人所指出的,这不会很好地发挥作用。通过将代码移动到App#u code文件夹中它自己的c#类中,所有东西都可以访问它。谢谢你的帮助 你有你的类的实例可以从中访问吗?你想从StudentList中访问Student吗?我在想这样的事情。。。学生=新学生(学生ID、名字、姓氏、当前学期、大学开始日期、专业);然而,这对梅不起作用,我在找这样的东西。。。学生=新学生(学生ID、名字、姓氏、当前学期、大学开始日期、专业);你说得对。通过将代码移动到App#u code文件夹中它自己的c#类中,所有东西都可以访问它。谢谢你的帮助!我没有正确设置自动属性的原因是,我需要证明我可以通过公共属性访问私有变量。感谢您提供有关将代码分离到n层体系结构的提示。它帮助我记住,我需要将代码移动到App_code文件夹中它自己的类中,这样我就可以从任何地方访问它。谢谢
private int StudentID;
public int studentID
{
get
{
return StudentID;
}
set
{
StudentID = value;
}
}
public int StudentId { get; set; }