C#之set與get方法的用法案例
更新時間:2021年08月03日 08:28:35 作者:懸弧
這篇文章主要介紹了C#之set與get方法的用法案例,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
需求:學(xué)生輸入姓名和語文、數(shù)學(xué)、英語,編程求出總分和平均分,并在屏幕上顯示XX的總分和平均分
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//學(xué)生輸入姓名和語文、數(shù)學(xué)、英語,編程求出總分和平均分,并在屏幕上顯示XX的總分和平均分
namespace Student_management_system
{
class Student
{
private String name; //學(xué)生姓名
private int chinese; //語文成績
private int math; //數(shù)學(xué)成績
private int english; //英語成績
public String student_name //這個不是一個方法,它是一個變量,當(dāng)對象調(diào)用該變量時,就要給這個對象的name屬性賦值,或者獲取該變量的值
{
set{ //直接在里面定義set方法,這樣對象就可以通過這樣調(diào)用來賦值了,如 Student s;s.student_name="唐僧";
this.name=value;
}
get{ //定義get方法,對象可以這樣獲取get方法里面返回來的name值,如s.student_name;
return name;
}
}
public int student_chinese
{
set
{
this.chinese = value;
}
get
{
return this.chinese;
}
}
public int student_math
{
set
{
this.math = value;
}
get
{
return this.math;
}
}
public int student_english
{
set
{
this.english = value;
}
get
{
return this.english;
}
}
public Student(String name, int chinese, int math, int english)
{
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
public int sum() //求總分
{
int sum = this.chinese + this.english + this.math;
return sum;
}
public float average() //求平均分
{
float avg = sum() / 3;
return avg;
}
static void Main(string[] args)
{
Student s = new Student();
Console.WriteLine("請輸入學(xué)生姓名");
s.student_name = Console.ReadLine();
Console.WriteLine("請輸入學(xué)生科目成績:");
s.student_chinese =Convert.ToInt32(Console.ReadLine());
s.student_english = Convert.ToInt32(Console.ReadLine());
s.student_math = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(s.name + "的語文是" + s.student_chinese + "分,數(shù)學(xué)是" + s.student_math + "分,英語是" + s.student_english + "分,總分:" + s.sum()+",平均分:" + s.average());
s.student_chinese = 69;
s.student_math = 100;
Console.WriteLine("修改分?jǐn)?shù)后-->" + s.name + "的語文是" + s.student_chinese + "分,數(shù)學(xué)是" + s.student_math + "分,英語是" + s.student_english + "分,總分:" + s.sum() + ",平均分:" + s.average());
//加上這句話,否則一運行就會閃退,即剛出現(xiàn)命令窗口就會馬上消失
Console.ReadLine();
}
}
}
運行結(jié)果:

到此這篇關(guān)于C#之set與get方法的用法案例的文章就介紹到這了,更多相關(guān)C#之set與get方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
讓C# Excel導(dǎo)入導(dǎo)出 支持不同版本Office
讓C# Excel導(dǎo)入導(dǎo)出,支持不同版本的Office,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-08-08

