C# 如何检索类属性的属性值?
是否可以从c中的自定义属性类检索公共成员。考虑下面的属性类:C# 如何检索类属性的属性值?,c#,.net-core,C#,.net Core,是否可以从c中的自定义属性类检索公共成员。考虑下面的属性类: [AttributeUsage(AttributeTargets.Class, Inherited = false)] public class ModuleMessageHandlerAttribute : Attribute { public Type type { get; set; } public ModuleMessageHandlerAttribute(Type type) {
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class ModuleMessageHandlerAttribute : Attribute
{
public Type type { get; set; }
public ModuleMessageHandlerAttribute(Type type)
{
this.type = type;
}
}
我有一些处理程序类,如下所示,它们使用这个属性:
[ModuleMessageHandler(typeof(HelloModule))]
public class HelloMessageHandler : IMessageHandler<Hello>
{
}
接下来,我需要访问ModuleMessageHandlerAttributeclass的Type属性,以比较该类型是否与特定类匹配。您的意思是:
[ModuleMessageHandler(typeof(SomeType))]
class SomeClass
{
void SomeMethod()
{
ModuleMessageHandlerAttribute attribute = GetType()
.GetCustomAttribute<ModuleMessageHandlerAttribute>();
Type type = attribute.type;
}
}
你的意思是这样的:
[ModuleMessageHandler(typeof(SomeType))]
class SomeClass
{
void SomeMethod()
{
ModuleMessageHandlerAttribute attribute = GetType()
.GetCustomAttribute<ModuleMessageHandlerAttribute>();
Type type = attribute.type;
}
}
你可以用反射来达到这个目的
var result = assembly.GetTypes()
.Where(x=> x.GetCustomAttributes<ModuleMessageHandlerAttribute>().Any())
.Select(x=>x.GetCustomAttribute<ModuleMessageHandlerAttribute>().type);
如果要检索属性的所有公共属性,则可以使用
IEnumerable<IEnumerable<KeyValuePair<string,object>>> GetTypesAttribute<T>(Assembly assembly) where T:Attribute
{
return assembly.GetTypes().Where(x=> x.GetCustomAttributes(typeof(T)).Any())
.Select(x=> x.GetCustomAttribute(typeof(T)))
.Select(x=> x.GetType().GetProperties().Select(c=> new KeyValuePair<string,object>(c.Name,c.GetValue(x))));
}
您现在可以将该方法用作
GetTypesAttribute<ModuleMessageHandlerAttribute>(assembly);
你可以用反射来达到这个目的
var result = assembly.GetTypes()
.Where(x=> x.GetCustomAttributes<ModuleMessageHandlerAttribute>().Any())
.Select(x=>x.GetCustomAttribute<ModuleMessageHandlerAttribute>().type);
如果要检索属性的所有公共属性,则可以使用
IEnumerable<IEnumerable<KeyValuePair<string,object>>> GetTypesAttribute<T>(Assembly assembly) where T:Attribute
{
return assembly.GetTypes().Where(x=> x.GetCustomAttributes(typeof(T)).Any())
.Select(x=> x.GetCustomAttribute(typeof(T)))
.Select(x=> x.GetType().GetProperties().Select(c=> new KeyValuePair<string,object>(c.Name,c.GetValue(x))));
}
您现在可以将该方法用作
GetTypesAttribute<ModuleMessageHandlerAttribute>(assembly);
从使用此属性的所有类访问type属性的含义是什么?解释更多..类中是否存在类型属性?你如何在其他课堂上使用它?如果只是将值传递给ModuleMessageHandler,则应该能够传递vlaue。在本部分中,我希望从使用此属性的所有类访问type属性。没有意义。从使用此属性的所有类访问type属性有什么意义?解释更多..类中是否存在类型属性?你如何在其他课堂上使用它?如果只是将值传递给ModuleMessageHandler,则应该能够传递vlaue。在本部分中,我希望从使用此属性的所有类访问type属性。没有道理。