Skip to content

Instantly share code, notes, and snippets.

@voquanghoa
Last active November 27, 2017 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voquanghoa/9e1cd03d877d5c121237a12611db6085 to your computer and use it in GitHub Desktop.
Save voquanghoa/9e1cd03d877d5c121237a12611db6085 to your computer and use it in GitHub Desktop.
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;
}
}
}
@voquanghoa
Copy link
Author

Refactor

  • Tách file cho từng class
  • Đưa GetAttributeValue vào class riêng extension class
    ....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment