C# 快速访问类型/方法/。。。在C中保存属性的#
我在这里创建了一个名为aaAttribute的自定义属性,例如一个名为B的类,其中一个或多个方法使用该属性。在不遍历整个程序集并查看所有已定义的属性方法的情况下,是否可以获取将属性(在本例中为BMethod1)作为其属性之一的方法的MethodInfo?它们是其他属性获取(参数/类型/属性/…)的类似方式吗?我不想要一个包含所有使用该类型属性的方法的数组,只想要一个包含这个AtterBute对象的方法。我想用它对方法施加额外的约束(返回类型、参数、名称、其他属性用法等)C# 快速访问类型/方法/。。。在C中保存属性的#,c#,attributes,methodinfo,system.reflection,C#,Attributes,Methodinfo,System.reflection,我在这里创建了一个名为aaAttribute的自定义属性,例如一个名为B的类,其中一个或多个方法使用该属性。在不遍历整个程序集并查看所有已定义的属性方法的情况下,是否可以获取将属性(在本例中为BMethod1)作为其属性之一的方法的MethodInfo?它们是其他属性获取(参数/类型/属性/…)的类似方式吗?我不想要一个包含所有使用该类型属性的方法的数组,只想要一个包含这个AtterBute对象的方法。我想用它对方法施加额外的约束(返回类型、参数、名称、其他属性用法等) 要确定某个方法是否应用了
要确定某个方法是否应用了属性,您已经拥有MethodInfo 如果我正确理解了您的问题,您希望在属性代码中获得应用属性的对象(本例中的方法)。
var type = obj.GetType();
foreach(var method in type.GetMethods())
{
var attributes = method.GetCustomAttributes(typeof(AAtribute));
if(attributes.Length > 0)
{
//this method has AAtribute applied at least once
}
}
我很确定没有直接的方法可以做到这一点——属性不知道它所连接的对象,这种关联是另一种方式
我能向您推荐的最佳解决方案如下:
using System;
using System.Reflection;
namespace test {
[AttributeUsage(AttributeTargets.Method)]
public class AAttribute : Attribute {
public AAttribute(Type type,string method) {
MethodInfo mi = type.GetMethod(method);
}
}
public class B {
[A(typeof(B),"BMethod1")]
public void BMethod1() {
}
}
}
注意通过访问属性构造函数中的MethodInfo,您希望实现什么?也许有另一种方法可以实现你的目标 编辑 作为另一种可能的解决方案,您可以在属性中提供一个执行检查的静态方法,但这涉及到迭代MethodInfos
using System;
using System.Reflection;
namespace test {
[AttributeUsage(AttributeTargets.Method)]
public class AAttribute : Attribute {
public static void CheckType<T>() {
foreach (MethodInfo mi in typeof(T).GetMethods()) {
AAttribute[] attributes = (AAttribute[])mi.GetCustomAttributes(typeof(AAttribute), false);
if (0 != attributes.Length) {
// do your checks here
}
}
}
}
public class B {
[A]
public void BMethod1() {
}
[A]
public int BMethod2() {
return 0;
}
}
public static class Program {
public static void Main() {
AAttribute.CheckType<B>();
}
}
}
使用系统;
运用系统反思;
名称空间测试{
[AttributeUsage(AttributeTargets.Method)]
公共类aa属性:属性{
公共静态无效检查类型(){
foreach(typeof(T).GetMethods()中的MethodInfo mi){
AAttribute[]属性=(AAttribute[])mi.GetCustomAttributes(typeof(AAttribute),false);
如果(0!=attributes.Length){
//请在这里结账
}
}
}
}
公共B级{
[A]
公共无效方法1(){
}
[A]
公共int BMethod2(){
返回0;
}
}
公共静态类程序{
公共静态void Main(){
aaAttribute.CheckType();
}
}
}
我认为答案是否定的,或者至少不合理。只有在通过MethodInfo查找属性后,才会构造该属性的实例。实例化具有该属性的方法的类不会实例化该属性。属性实例只有在您开始通过反射查找它们时才会创建。好问题,我也想知道答案……是的,但是如何从属性内部执行?有没有办法知道属性的当前实例应用于哪个方法(或成员)?正如我已经说过的,我想对它施加额外的约束(返回类型、参数数量、参数类型、方法名称等)。如果该方法无效,则可能引发异常。但是不管原因是什么,你可以访问属性链接的地方,这难道不是逻辑吗?是的,但是你想用这些约束做什么呢?在任何情况下,在您尝试反映类型之前,都不会实例化该属性。
var type = obj.GetType();
foreach(var method in type.GetMethods())
{
var attributes = method.GetCustomAttributes(typeof(AAtribute));
if(attributes.Length > 0)
{
//this method has AAtribute applied at least once
}
}