在我MiddleTier項目回來解決方案,我有客戶類,與ATTRIBUTE1無法獲取屬性從GetCustomAttributes
public class Customer2
{
public string Name2 { get; set; }
public int Age2 { get; set; }
}
[MyAttribute1]
public class Customer1
{
[MyAttribute1(DefaultValue = "Must Enter Name")]
public string Name { get; set; }
[MyAttribute1(DefaultValue = "Must Enter Age")]
public int Age { get; set; }
}
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute1 : Attribute
{
public string DefaultValue { get; set; }
}
定義他們中的一個在一個單獨的項目中,我引用MiddleTier DLL,我想列舉通過該DLL中的所有類並標識與Attribute1關聯的Customer1類。
Assembly assembly = Assembly.LoadFrom(@"C:\myfolder\MiddleTier\bin\Debug\MiddleTier.dll");
foreach (Type type in assembly.GetTypes())
{
var attribs = type.GetCustomAttributes(typeof(MyAttribute1), false); <--- problem
if (attribs != null && attribs.Length > 0)
{
....
}
}
我不是由GetCustomAttributes電話獲取任何屬性回來。我究竟做錯了什麼?請幫忙。由於
我猜測,運行時可能以某種方式考慮爲MiddleTier.dll編譯的「MyAttribute1」類型與在當前域的運行時加載的「MyAttribute1」類型不同。 – 2012-07-16 19:26:02
您可以嘗試調用非類型重載'GetCustomAttributes(false)',然後檢查條目的類型。像'if(attribs.Length> 0){Console.WriteLine(attribs [0] .GetType()== typeof(MyAttribute1)); }' – 2012-07-16 19:27:32