You can not get any info about the class which contains members which are decorated by some attribute, inside the attributes constructor, as I already pointed out in my previous answer here.
Instance to Attribute
But i suggested a solution, which is to invoke a method inside your attribute instead of using the constructor, and this will basically get you the same result.
I have reworked my previous answer a bit to solve your problem in the following way.
Your attribute will now need to use the following method instead of the constructor.
[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute
{
public void MyAttributeInvoke(object source)
{
source.GetType()
.GetProperties()
.ToList()
.ForEach(x => Console.WriteLine(x.Name));
}
}
And your Test class will need to have the following piece of code inside its constructor.
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; }
}
By running the following lines of code, you will notice that you can access both properties from the Test class from your attribute.
class Program
{
static void Main()
{
new Test();
Console.Read();
}
}