3
[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 to access square() in main() or in any other class with the help of MethodId?

1 Answer 1

9
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 meant to display how to do it. Not omptimised for performance. Ideally you would cache the methodInfos.

Sign up to request clarification or add additional context in comments.

4 Comments

Please explain : methodInfo.Invoke(new Methods(), null);
The method is not static so you need an instance to run it, hence new Methods(). The other one is the parameters which it has none hence null.
Ok...But "new Methods()" is an instance created to call which method? It is just a new object.I am not able to catch this. What are we passing exactly? :)
You need to read the reflection stuff. I cannot explain it here in comments. Read about MethodInfo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.