Last active
November 27, 2017 03:53
-
-
Save voquanghoa/9e1cd03d877d5c121237a12611db6085 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
namespace ModelEasy | |
{ | |
public class IgnoreInputAttribute : Attribute | |
{ | |
} | |
public class PrompDisplayAttribute : Attribute | |
{ | |
public string Display { get; set; } | |
public PrompDisplayAttribute(string display) | |
{ | |
Display = display; | |
} | |
} | |
public class EasyModel | |
{ | |
private readonly List<PropertyInfo> propertyInfos; | |
public EasyModel() | |
{ | |
propertyInfos = GetType().GetProperties().ToList(); | |
} | |
[IgnoreInput] | |
public int Id { get; set; } | |
[PrompDisplay("Ten hoc sinh ")] | |
public string Name { get; set; } | |
[PrompDisplay("Diem trung binh")] | |
public int Score { get; set; } | |
public void Input() | |
{ | |
foreach (var propertyInfo in propertyInfos.Where(x=>x.CanWrite)) | |
{ | |
var prompDisplay = GetAttribute<PrompDisplayAttribute>(propertyInfo); | |
var ignoreInput = GetAttribute<IgnoreInputAttribute>(propertyInfo); | |
if (ignoreInput == null) | |
{ | |
Console.Write($"Nhap {prompDisplay?.Display ?? propertyInfo.Name}: "); | |
switch (Type.GetTypeCode(propertyInfo.PropertyType)) | |
{ | |
case TypeCode.String: | |
propertyInfo.SetValue(this, Console.ReadLine()); | |
break; | |
case TypeCode.Int16: | |
propertyInfo.SetValue(this, Convert.ToInt16(Console.ReadLine())); | |
break; | |
case TypeCode.Int32: | |
propertyInfo.SetValue(this, Convert.ToInt32(Console.ReadLine())); | |
break; | |
} | |
} | |
} | |
} | |
public override string ToString() | |
{ | |
return string.Join(", ", propertyInfos | |
.Where(x => x.CanRead) | |
.Select(x => $"{x.Name}: {x.GetValue(this)}")); | |
} | |
private static T GetAttribute<T>(PropertyInfo propertyInfo) where T: Attribute | |
{ | |
return propertyInfo.GetCustomAttributes(typeof(T), true).FirstOrDefault() as T; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refactor
extension class
....