/// <summary>
/// 获取属性中所有被特性标记的
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public string ReturnToReality<T>(T obj) where T : class, IStu
{
//获取类型
Type type = obj.GetType();
//真实的名称
List<string> stringList= new List<string>();
//获取该类型所有的属性
var propList = type.GetProperties();
//循环所有的属性
foreach (PropertyInfo prop in propList)
{
string Pro = prop.Name;
if (prop.IsDefined(typeof(StuAttribute)))
{
//得到该特性
var tp = prop.GetCustomAttribute<StuAttribute>();
if (tp != null)
{
//取该特性的值
Pro = tp.StuName;
}
}
stringList.Add(Pro);
}
return string.Join(",", stringList);
}
/***********************************以下是特性********************************************/
/// <summary>
/// 特性标记为 只能给属性标记
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class StuAttribute:Attribute
{
public string StuName;
public StuAttribute(string stuName)
{
this.StuName = stuName;
}
}
/*************************实体 **************接口IStu 是起标记作用 接口中什么都没有*******/
public class Student:IStu
{
public int Id { get; set; }
[Stu("SName")]
public string Name { get; set; }
}