using System;
using System.Collections.Generic; // for HashSet
using System.Linq; // for using Where
using System.Reflection;
namespace attribute
{
public class Test
{
public static void Main()
{
var targetClasses = new HashSet<string>(new[] { "Foo", "Foo2" });
var targetFns = new HashSet<string>(new[] { "fn", "fn2", "fn3" });
foreach (var target in targetClasses){
foreach(var fn in targetFns){
var method = (target.GetType().GetTypeInfo()) // (typeof(Foo).GetTypeInfo())
.DeclaredMethods.Where(x => x.Name == fn).FirstOrDefault();
if (method != null) //return 0;
{
var customAttributes = (MyCustomAttribute[])method
.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
var myAttribute = customAttributes[0];
bool value = myAttribute.condition;
Console.WriteLine(value);
if (value == true)
method.Invoke(null, null);
else
Console.WriteLine("The attribute parameter is not as required");
}
}
}
}
}
}
}
namespace attribute
{
[AttributeUsage(AttributeTargets.All)]
public class MyCustomAttribute : Attribute
{
public bool condition { get; set; }
}
public class Foo
{
[MyCustom(condition= true ? ("bar" == "bar") : false)]
internal static void fn()
{
Console.WriteLine("a function in a class");
}
[MyCustom(condition= true ? (1 == 2) : false)]
internal static void fn2()
{
Console.WriteLine("another function in the same class");
}
}
public class Foo2
{
[MyCustom(condition= true ? (1 == 1) : false)]
internal static void fn2()
{
Console.WriteLine("another function in a nother class");
}
}
}