C# Setter和Getter方法是如何工作的?
在开始封装并学习如何使用属性之前,我正在研究setter和getter方法。C# Setter和Getter方法是如何工作的?,c#,C#,在开始封装并学习如何使用属性之前,我正在研究setter和getter方法。 我了解SetID和GetID方法的工作原理,但我不确定SetName、GetName和GetPassMark方法 using System; public class Student { private int _id; private string _Name; private int _PassMark = 35;
我了解
SetID
和GetID
方法的工作原理,但我不确定SetName
、GetName
和GetPassMark
方法
using System;
public class Student
{
private int _id;
private string _Name;
private int _PassMark = 35;
public void SetId(int Id)
{
if (Id<=0)
{
throw new Exception("Student Id cannot be negative");
}
this._id = Id;
}
public int GetId()
{
return this._id;
}
public void SetName(string Name)
{
if(string.IsNullOrEmpty(Name))
{
throw new Exception("Name cannot be null or empty");
}
this._Name = Name;
}
public string GetName()
{
if(string.IsNullOrEmpty(this._Name))
{
return "No Name";
}
else
{
return this._Name;
}
}
public int GetPassMark()
{
return this._PassMark;
}
}
public class Program
{
public static void Main()
{
Student C1 = new Student();
C1.SetId(101);
C1.SetName("Mark");
Console.WriteLine("ID = {0}" , C1.GetId());
Console.WriteLine("Student Name = {0}", C1.GetName());
Console.WriteLine("PassMark = {0}", C1.GetPassMark());
}
}
使用系统;
公立班学生
{
私人内部id;
私有字符串\u名称;
私有整数_PassMark=35;
公共无效集合Id(内部Id)
{
如果在创建对象时没有设置(Id,因为\u Name
。Student
对象可能有null
\u Name
。您可以通过在构造函数中设置\u Name
来修复它,然后您可以返回它
许多人喜欢使用这个
,即使它不是真正必要的,因为它使代码更加明显。这只是一个语法偏好。看起来你来自Java。如果你使用peoperties,你可以实现自动属性,而不必创建特殊的getter和setter。