一:获取属性特性
namespace Test
{
internal class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "lilei";
string name_d = GetDecription();
Console.WriteLine(name_d);
Console.ReadLine();
}
public static string GetDecription()
{
Person person = new Person();
var field = person.GetType().GetProperty("Name");
var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
return customAttribute == null ? person.ToString() : ((DescriptionAttribute)customAttribute).Description;
}
}
class Person
{
[Description("this is name"), Category("Layout")]
public string Name { get; set; }
[Description("this is age"), Category("Layout")]
public int Age { get; set; }
}
}
二:用反射获取属性特性
namespace Test
{
internal class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "lilei";
string name_d = GetDecription();
Console.WriteLine(name_d);
Console.ReadLine();
}
public static string GetDecription()
{
string str = "";
PropertyInfo pi = typeof(Person).GetProperty("Name");
foreach (object obj in pi.GetCustomAttributes(false))
{
if (obj is DescriptionAttribute)
{
str += (obj as DescriptionAttribute).Description;
}
}
return str;
}
}
class Person
{
[Description("this is name"), Category("Layout")]
public string Name { get; set; }
[Description("this is age"), Category("Layout")]
public int Age { get; set; }
}
}
三:
//public static string BB()
//{
// string str = "";
// Person person = new Person();
// AttributeCollection attributes = TypeDescriptor.GetAttributes(person.GetType().GetProperty("Name"));
// DescriptionAttribute da = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
// if (attributes.Contains(da))
// {
// str += da.Description;
// }
// return str;
//}
public static void CC()
{
string str = "";
Type myType = typeof(Person);
foreach (object obj in myType.GetCustomAttributes(false))
{
if (obj is DescriptionAttribute)
{
str = (obj as DescriptionAttribute).Description;
}
}
}