【问题标题】:Getting the class which one of its members using custom attribute使用自定义属性获取其成员之一的类
【发布时间】:2013-07-27 06:06:38
【问题描述】:

我有这个自定义属性:

[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute
{
    public MyAttribute()
    {
         // I want to get the Test type in here. 
         // it could be any kind of type that one of its members uses this attribute. 
    }
}

我在某处使用 MyAtrribute。

public class Test
{
    [MyAttribute]
    public void MyMethod()
    {
        //method body
    }

    public string Name{get;set;}

    public string LastName{get;set;}
}

我的问题是,我可以从 MyAttribute 的构造函数中获取测试类的其他成员吗?

感谢您的帮助!

【问题讨论】:

  • 你能从MyAttribute的构造函数中得到MyMethod成员吗?
  • @lazyberezovsky 我不确定。我想我可以做 Assembly.GetCallingAssembly().GetTypes().... 但是,问题是我可能在一个程序集中有两个命名空间,它们具有完全相同的类和使用 MyAttribute 的相同方法。
  • @aevitas 你能解释一下副本在哪里吗?您引用的链接完全不同。
  • @Dilshod 没有阅读您发布的作为对我的答案的评论的附加信息,它实际上看起来像是重复的。您应该考虑进行编辑,因为您在编译时不知道要获取成员的类型 - 这将使其成为一个完全不同的问题。

标签: c# reflection attributes custom-attributes


【解决方案1】:

您无法在属性构造函数中获取有关包含由某些属性修饰的成员的类的任何信息,正如我在之前的回答中已经指出的那样。

Instance to Attribute

但我建议了一个解决方案,即在属性中调用方法而不是使用构造函数,这基本上会得到相同的结果。

我已经修改了我之前的答案,以通过以下方式解决您的问题。

您的属性现在需要使用以下方法而不是构造函数。

[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute
{
    public void MyAttributeInvoke(object source)
    {
        source.GetType()
              .GetProperties()
              .ToList()
              .ForEach(x => Console.WriteLine(x.Name));
    }
}

您的 Test 类将需要在其构造函数中包含以下代码。

public class Test
{
    public Test()
    {
        GetType().GetMethods()
                 .Where(x => x.GetCustomAttributes(true).OfType<MyAttribute>().Any())
                 .ToList()
                 .ForEach(x => (x.GetCustomAttributes(true).OfType<MyAttribute>().First() as MyAttribute).MyAttributeInvoke(this));
    }

    [MyAttribute]
    public void MyMethod() { }

    public string Name { get; set; }

    public string LastName { get; set; }
}

通过运行以下代码行,您会注意到您可以通过属性访问 Test 类的两个属性。

class Program
{
    static void Main()
    { 
        new Test();

        Console.Read();
    }
}

【讨论】:

  • 要查找使用某个属性的所有方法,可以通过遍历当前(或所有,或特定)程序集中所有类中的所有方法来完成。这就是一些反射库所提供的以及一些代码注入工具集的工作方式。此外,您可以将当前类类型作为参数提供给属性,但我不明白为什么需要这样做,属性已经绑定到方法、属性、字段、类或事件。跨度>
【解决方案2】:

不,您无法在属性的构造函数中获取任何上下文信息。

属性的生命周期也与它们关联的项目有很大不同(即,直到有人真正要求属性时才创建它们)。

拥有关于其他类成员的逻辑的更好地方是检查类成员是否具有给定属性的代码(因为此时代码具有关于类/成员的信息)。

【讨论】:

    【解决方案3】:

    不,你不能。属性的构造函数不可能知道它装饰方法的类型。

    【讨论】:

    • 请注意,您的回答似乎与问题无关:“从MyAttribute 的构造函数中获取Test 类的其他成员”...
    • 我知道如何获取类的方法或其他成员,但我的问题是我还不知道类型。
    • @AlexeiLevenkov 它会做到这一点。然而,它何时会这样做是完全不同的事情。
    • @aevitas - 我想我遗漏了一些东西 - 你建议如何获取包含 MyAttribute 关联的成员的类的 Type
    • @AlexeiLevenkov 不,您确实是正确的,您无法获取使用属性的外部类型。然而,就目前而言,这个问题有很多误解,我可能解释错了。
    猜你喜欢
    • 2010-10-12
    • 1970-01-01
    • 2014-02-25
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多