111,092
社区成员




List<Test> test = new List<Test>();
foreach (var item in test)
{
//1. 根据test.name查找Description特性等于test.name的属性
}
List<PropertyInfo> properties = type.GetProperties(BindingFlags.Public |BindingFlags.NonPublic | BindingFlags.Instance).ToList();
Func<PropertyInfo, bool> filter = a => ((DescriptionAttribute)a.GetCustomAttributes(typeof(DescriptionAttribute),true).FirstOrDefault()).Description== name;
PropertyInfo property = properties.Where(filter).FirstOrDefault();
bool value = Convert.ToBoolean(property.GetValue(software, null));//取值
property.SetValue(software, !value, null);//赋值
结贴给分!
[Description("微信")]
public bool WeChat{get;set}
[/quote]
你的意思是通过这个字段的描述获得字段的属性吧。
[Description("微信")]
public bool WeChat{get;set}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var typeList = GetEnumDescriptionList<Data>();
// 获取 Key、Value
foreach (var item in typeList.ToList())
{
Console.Write($" Key :{item.Key} ,Value:{item.Value} \n");
}
Console.WriteLine();
}
public static List<KeyValuePair<string, string>> GetEnumDescriptionList<T>()
{
List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
FieldInfo[] fields = typeof(T).GetFields();
foreach (FieldInfo field in fields)
{
object[] attr = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
string description = attr.Length == 0 ? field.Name : ((DescriptionAttribute)attr[0]).Description;
result.Add(new KeyValuePair<string, string>(field.Name, description));
}
return result;
}
}
public class Data
{
[Description("名称")]
public string name;
[Description("年龄")]
public int age;
}
}
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
object n = new A();
foreach (var p in n.GetType().GetProperties())
{
var attr = p.GetCustomAttributes(typeof(MyDesc), true);
if (attr.Length > 0 && attr[0] is MyDesc d)
Console.WriteLine($"prop {p.Name} desc s is {d.S}");
p.SetValue(n, 1234);
Console.WriteLine($"prop is {p.GetValue(n)}");
}
Console.WriteLine("..................按任意键结束程序");
Console.ReadKey();
}
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class MyDesc : Attribute
{
public MyDesc(bool n, string s)
{
this.L = n;
this.S = s;
}
public string S { get; private set; }
public bool L { get; set; }
}
public class A
{
int _pp;
[MyDesc(true, "aaa")]
public int PP
{
get
{
return _pp;
}
set
{
_pp = value;
}
}
}
}