By GokiSoft.com|
09:22 30/10/2021|
C Sharp
[Share Code] Bài tập ôn luyện OOP + Interface trong C# - Lập Trình C# - Lập Trình C Sharp
Bài tập ôn luyện OOP + Interface trong C# - Lập Trình C# - Lập Trình C Sharp
#Program.cs
using System;
using System.Collections.Generic;
namespace BT1506
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Nhap id: ");
int id = int.Parse(Console.ReadLine());
Console.WriteLine("Nhap ten: ");
string name = Console.ReadLine();
Console.WriteLine("Nhap ky nang: ");
string skills = Console.ReadLine();
Console.WriteLine("Nhap DOB (yyyy-MM-dd): ");
string dobStr = Console.ReadLine();
DateTime dob = ConvertStringToDateTime(dobStr);
Programmer programmer = new Programmer(skills, dob, id, name);
programmer.ShowInfo();
//Yeu cau tao mang List co capacity = 3;
List<Programmer> programmers = new List<Programmer>();
List<Programmer> list = new List<Programmer>(3);
list.Add(programmer);
list.Add(programmer);
list.Add(programmer);
list.Add(programmer);
list.Add(programmer);
list.Add(programmer);
list.Add(programmer);
foreach (Programmer p in list)
{
p.ShowInfo();
}
}
static DateTime ConvertStringToDateTime(string str)
{
DateTime myDate = DateTime.ParseExact(str, "yyyy-MM-dd",
System.Globalization.CultureInfo.InvariantCulture);
return myDate;
}
}
}
#IPerson.cs
using System;
namespace BT1506
{
/**
* Tat cac thuoc tinh & methods -> public
*/
public interface IPerson
{
string Skills { get; set; }
DateTime DateOfBirth { get; }
int Age { get; }
}
}
#Employee.cs
using System;
namespace BT1506
{
public abstract class Employee
{
private int _id;
public int ID
{
get
{
return _id;
}
}
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if(value.Length < 3)
{
throw new Exception();
}
_name = value;
}
}
public Employee(int id)
{
_id = id;
Name = "No Name";
}
public Employee(int id, string name) : this(id)
{
Name = name;
}
public abstract void ShowInfo();
}
}
#Programmer.cs
using System;
namespace BT1506
{
public class Programmer : Employee, IPerson
{
string _skills;
public string Skills {
get
{
return _skills;
}
set
{
if(value.Length == 0)
{
throw new Exception();
}
_skills = value;
}
}
DateTime _DOB;
public DateTime DateOfBirth {
get
{
return _DOB;
}
set
{
_DOB = value;
}
}
int _age;
public int Age {
get
{
int year = int.Parse(DateOfBirth.ToString("yyyy"));
int currentYear = int.Parse(DateTime.Now.ToString("yyyy"));
_age = currentYear - year;
return _age;
}
}
public Programmer(int id, string name):base(id, name)
{
_skills = string.Empty;
DateOfBirth = DateTime.Now;
}
public Programmer(string skills, DateTime dob, int id, string name) : base(id, name)
{
Skills = skills;
DateOfBirth = dob;
}
public override void ShowInfo()
{
Console.WriteLine("Id: {0} | Name: {1} | Skills: {2} | DOB: {3} | Age: {4}",
ID, Name, Skills, DateOfBirth, Age);
}
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)