[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()
    {        }
}




如何在MethodId的帮助下在main()或任何其他类中访问square()?

最佳答案

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();
}


和用法:

var methodInfo = GetMethodInfo(1);
methodInfo.Invoke(new Methods(), null);


注意:

此解决方案仅用于显示操作方法。没有对性能进行优化。理想情况下,您将缓存methodInfos。

10-08 15:18