【问题标题】:Calling method with attribute value in C#在 C# 中调用具有属性值的方法
【发布时间】:2012-04-09 20:55:06
【问题描述】:
[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()?

【问题讨论】:

    标签: c# c#-4.0 properties invoke custom-attributes


    【解决方案1】:
    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。

    【讨论】:

    • 请解释一下:methodInfo.Invoke(new Methods(), null);
    • 该方法不是静态的,因此您需要一个实例来运行它,因此new Methods()。另一个是它没有的参数,因此null.
    • 好的...但是“new Methods()”是一个实例,是为了调用哪个方法而创建的?这只是一个新对象。我无法捕捉到它。我们到底在传递什么? :)
    • 你需要阅读反射的东西。我无法在 cmets 中解释它。阅读MethodInfo
    猜你喜欢
    • 1970-01-01
    • 2018-03-03
    • 2019-03-30
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 2014-02-14
    相关资源
    最近更新 更多