【发布时间】:2013-07-16 03:24:02
【问题描述】:
所以我正在尝试使用反射从 C# 中的自定义属性访问数据,我所拥有的是:
属性类:
[System.AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)]
public class Table : System.Attribute
{
public string Name { get; set; }
public Table (string name)
{
this.Name = name;
}
}
我有一个单独的程序集,其中包含以下内容:
[Table("Data")]
public class Data
{
public int PrimaryKey { get; set; }
public string BankName { get; set; }
public enum BankType { City, State, Federal };
}
在主程序中我枚举了当前目录下的所有文件,并过滤了所有的dll文件。一旦我有我运行的 dll 文件:
var asm = Assembly.LoadFile(file);
var asmTypes = asm.GetTypes();
从这里我尝试使用 Assembly 方法加载 Table 属性:GetCustomAtteribute(Type t, bool inherit)
但是,Table 属性不会显示在任何 dll 中,也不会显示为程序集中加载的任何类型。
任何想法我做错了什么?
提前致谢。
更新:
这是遍历类型并尝试提取属性的代码:
foreach (var dll in dlls)
{
var asm = Assembly.LoadFile(dll);
var asmTypes = asm.GetTypes();
foreach (var type in asmTypes)
{
Table.Table[] attributes = (Table.Table[])type.GetCustomAttributes(typeof(Table.Table), true);
foreach (Table.Table attribute in attributes)
{
Console.WriteLine(((Table.Table) attribute).Name);
}
}
}
【问题讨论】:
-
显示枚举类型的确切代码。我敢打赌,您在
typeof中引用了错误的Table类... -
您留下了代码中最重要的部分,即使用 GetCustomAttribute 加载属性的部分。
-
对于
asmTypes中的每一项,您必须调用GetCustomAttributes。 -
还不清楚“加载表属性”与使用
GetCustomAttribute相关的含义,它获取应用于实体的属性列表... -
在你的属性类
Table中,将Name的设置器设为私有,否则在应用属性时可以设置两次,所以使用public string Name { get; private set; }。
标签: c# .net reflection .net-4.0 attributes