Call method with attribute value in C #
[AttributeUsage(AttributeTargets.Method,AllowMultiple=true)]
public class MethodId : Attribute
{
private int mId;
public MethodId(int mId)
{
this.mId = mId;
}
public int methodId
{
get { return this.mId; }
set { this.mId = value; }
}
}
public class Methods
{
[MethodId(1)]
public void square()
{ }
[MethodId(2)]
public void Notify()
{ }
}
How can I access square () in main () or any other class using MethodId?
+3
source to share
1 answer
private static MethodInfo GetMethodInfo(int id)
{
return typeof(Methods).GetMethods().
Where(x => x.GetCustomAttributes(false).OfType<MethodId>().Count() > 0)
.Where(x => x.GetCustomAttributes(false).OfType<MethodId>().First().methodId == id)
.First();
}
And usage:
var methodInfo = GetMethodInfo(1);
methodInfo.Invoke(new Methods(), null);
Note:
This solution is only intended to show you how to do this. Not recommended for performance. Ideally, you would cache the Infos.
+8
source to share