解决方案 一个控制台程序
下载地址
using System;
namespace Study.Reflect.Filter
{
[AttributeUsage(AttributeTargets.Property)]
internal class ColumnAttribute : Attribute
{
public string ColumnName { get; set; }
public ColumnAttribute(string columnName)
{
this.ColumnName = columnName;
}
}
}
using Study.Reflect.Filter;
using System.Reflection;
namespace Study.Reflect.Extend
{
internal static class AttributeHandle
{
public static string GetCodeAttributeValue(this PropertyInfo property)
{
var attrs = property.GetCustomAttributes(true);
foreach (var attr in attrs)
{
if (attr is ColumnAttribute)
{
var code = (attr as ColumnAttribute).ColumnName;
if (!string.IsNullOrEmpty(code)) return (attr as ColumnAttribute).ColumnName;
}
}
return property.Name;
}
}
}
using Study.Reflect.Filter;
namespace Study.Reflect.Model
{
internal class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
[ColumnAttribute("familyaddress")]
public string FamilyAddress { get; set; }
}
}
Main 函数
using Study.Reflect.Extend;
using Study.Reflect.Model;
using System;
using System.Linq;
using System.Reflection;
namespace Study.Reflect
{
internal class Program
{
static void Main(string[] args)
{
var type = typeof(Student);
PropertyInfo[] propertyInfos = type.GetProperties();
foreach (var property in propertyInfos)
{
Console.WriteLine(property.Name.ToString());
}
Console.WriteLine(string.Join(",", propertyInfos.Select(p => p.GetCodeAttributeValue())));
Console.ReadKey();
}
}
}
打印结果