使用C#中的反射从程序集中获取属性值
问题描述:
我检查了这段代码,但是它给出了错误信息!
I checked this code, but it gives an error message!
// load assembly
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(openFileDialog1.FileName);
var settingsType = assembly.GetTypes();
foreach (var form in settingsType)
{
//var propList = form.GetProperties().Where(p => p.GetCustomAttributes(typeof(Aviation.Library.CS.Libs.TransactionAttribute), true).Length != 0).ToList();
var propList = form.GetProperties().ToList();
foreach (PropertyInfo btn in propList)
{
System.Reflection.PropertyInfo defaultProperty = form.GetProperty(btn.Name);
object defaultObject = defaultProperty.GetValue(assembly, null);
}
}
错误信息是:
对象与目标类型不匹配。
The error message is:
"Object does not match target type."
答
我相信您用于读取自定义属性的代码不正确。请参阅以下链接阅读自定义属性
使用反射访问属性(C#编程指南) [ ^ ]
I believe code you are using for reading custom attributes is not correct. Pleas refer below link to reading custom attributes
Accessing Attributes With Reflection (C# Programming Guide)[^]