Skip to content

Instantly share code, notes, and snippets.

@voquanghoa voquanghoa/EasyModel.cs
Last active Nov 27, 2017

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Nov 27, 2017

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
You can’t perform that action at this time.