我有A
汇编MyCustomAttribute
。
现在我有大会B
,我在reference
汇编A
,我在汇编B
MyCustomAttribute
中使用。
现在我想在Assebmly B中获得MyCustomAttribute
的所有inctanses。
我试着像:
public static void Registration()
{
List<MyCustomAttribute> atrr = new List<MyCustomAttribute>();
var assembly = System.Reflection.Assembly.GetCallingAssembly();
var types = (from type in assembly.GetTypes()
where Attribute.IsDefined(type, typeof(MyCustomAttribute))
select type).ToList();
}
以及其他方式 - 但我无法获得MyCustomAttribute
。
更新
我的属性
namespace NamespaceOne.Attributes
{
[AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = false,
Inherited = false)]
public class MyCustomAttribute: Attribute
{
......
}
}
Now the second Assembly(second project - ASP WebApi):
namespace SecondNamespace.Controllers
{
public class HomeController : Controller
{
[MyCustomAttribute]
public ActionResult Index()
{
MyStaticMethod.Registration(); // THIS Class andmethod in First class library - where located attribute
ViewBag.Title = "Home Page";
return View();
}
答案 0 :(得分:1)
我试过了:
public class MyCustomAttribute : Attribute
{
}
[MyCustom]
public class SomeClassWithAttribute
{
}
然后在控制台中:
var assembly = typeof(SomeClassWithAttribute).Assembly;
var types = (from type in assembly.GetTypes()
where Attribute.IsDefined(type, typeof(MyCustomAttribute))
select type).ToList();
我在类型列表中获得了SomeClassWithAttribute。 @ C.Evenhuis是正确的,你可能在“GetCallingAssembly”方法中获得了错误的程序集。通过获取您知道的类型存在于该程序集中然后从中获取Assembly属性来获取程序集总是更可靠。
答案 1 :(得分:0)
试试这个:
public static void Registration()
{
List<RegistryAttribute> atrr = new List<RegistryAttribute>();
var assembly = System.Reflection.Assembly.GetCallingAssembly();
var types = assembly.GetTypes().Where(type =>
type.GetCustomAttributes().Any(x => x is typeof(MyCustomAttribute))).ToList();
}