当前位置:网站首页>获取属性特性几种方法
获取属性特性几种方法
2022-08-10 02:43:00 【zzyzxb】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace ConsoleApp3
{
internal class Program
{
public EventHandler<EventArgs> OnClick;
static void Main(string[] args)
{
Person person = new Person();
person.Name = "aoteman";
string s = GetDecription();
//AA();
//BB();
//CC();
//Console.WriteLine(ss);
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;
//string str = "";
//Desc desc = new Desc();
//PropertyDescriptor pd = TypeDescriptor.GetProperties(typeof(Desc))["des"];
//DescriptionAttribute description = pd == null ? null : pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
//str = description == null ? "" : description.Description;
string s = person.GetType().GetProperty("Name").GetGetMethod().Invoke(person, null).ToString();
}
public static void AA()
{
string str = "";
PropertyInfo pi = typeof(Desc).GetProperty("des");
foreach (object obj in pi.GetCustomAttributes(false))
{
if (obj is DescriptionAttribute)
{
str = (obj as DescriptionAttribute).Description;
}
}
}
public static void BB()
{
string str = "";
Desc desc = new Desc();
AttributeCollection attributes = TypeDescriptor.GetAttributes(desc);
DescriptionAttribute da = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
if (attributes.Contains(da))
{
str = da.Description;
}
}
public static void CC()
{
string str = "";
Type myType = typeof(Desc);
foreach (object obj in myType.GetCustomAttributes(false))
{
if (obj is DescriptionAttribute)
{
str = (obj as DescriptionAttribute).Description;
}
}
}
public static void ShowPerson(Person person)
{
int i = person?.Age ?? 0;
}
}
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 struct Desc
{
private byte val1;
[Description("一个属性")]
public byte des
{
get {
return val1; }
set {
val1 = value; }
}
}
}
边栏推荐
猜你喜欢
随机推荐
HRnet
2022.8.8考试游记总结
HRnet
Example 043: Scope, class methods and variables
2022.8.8考试从记忆中写入(memory)题解
(十四)时间延时任务及定时任务
从滑动标尺模型看企业网络安全能力评估与建设
第二十一章 源代码文件 REST API 参考(三)
【CC3200AI 实验教程5】疯壳·AI语音人脸识别(会议记录仪/人脸打卡机)-定时器
Research on IC enterprises
“双枪”木马病毒的进化史
yolov5+usb相机
plsql 查询数据库操作历史记录(Ctrl + e)
Error state based Kalman filter ESKF
驱动程序开发:按键中断之异步通知
On the Harvest of Travel
驱动程序开发:无设备树和有设备树的platform驱动
电子产品结构设计中的电磁兼容性(EMC)设计
2022.8.9 Remainder of Exam Balance--1000 Question Solutions
【Image Classification】2022-ResMLP