[英]Accessing attribute via reflection in C#
所以我試圖使用反射從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);
}
}
}
如果Table.Table
位於兩個程序集引用的單獨程序Table.Table
(即只有一個Table.Table
類型),那么這應該有效。 然而,這個問題表明有些不對勁。 我推薦做類似的事情:
foreach (var attrib in Attribute.GetCustomAttributes(type))
{
if (attrib.GetType().Name == "Table")
{
Console.WriteLine(attrib.GetType().FullName);
}
}
並在Console.WriteLine
上放置一個斷點,這樣你就可以看到發生了什么。 特別要看:
bool isSameType = attrib.GetType() == typeof(Table.Table);
bool isSameAssembly = attrib.GetType().Assembly == typeof(Table.Table).Assembly;
順便說一句,我強烈建議調用TableAttribute
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.