I created customized attribute named someAttribute
.
It has boolean member named Skip
:
public class someAttribute : Attribute
{
public bool Skip { get; set; }
}
In the Main
I initialized the member Skip
with the value true
for the method foo()
.
Next I am calling the function foo()
which has the attribute [someAttribute()]
and I want to check if the member Skip
was initialized:
[someAttribute()]
private static int foo()
{
if(Skip)
{
return 0;
}
return 1;
}
I received the error "The name 'Skip' does not exist in the current context".
How can I check the members of attribute inside a method that using this attribute ?
My full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ConsoleApplication1
{
class ProgramTest
{
[someAttribute()]
private static int foo()
{
if(Skip)
{
return 0;
}
return 1;
}
public class someAttribute : Attribute
{
public bool Skip { get; set; }
}
public static void initAttributes()
{
var methods = Assembly.GetExecutingAssembly().GetTypes().SelectMany(t => t.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
.Where(method => Attribute.IsDefined(method, typeof(someAttribute)));
foreach (MethodInfo methodInfo in methods)
{
IEnumerable<someAttribute> SomeAttributes = methodInfo.GetCustomAttributes<someAttribute>();
foreach (var attr in SomeAttributes)
{
attr.Skip = true;
}
}
}
static void Main(string[] args)
{
initAttributes();
int num = foo();
}
}
}
EDIT:
I added BindingFlags.Static
in order for the refelction to get the static function foo()
.