日期:2014-05-17  浏览次数:20848 次

调用Attribute的方法
本帖最后由 jiaoshiyao 于 2013-10-11 11:16:09 编辑

    public class CallContextAttribute : Attribute
    {
        public void SayHi(string abc) { }
    }
    [CallContext]
    class WhereAreYouLocation
    {
        public void SayLocation()
        {
            //这里怎么表用上面标记头CallContext的SayHi方法
        }
    }

------解决方案--------------------
var callContext = (CallContextAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(CallContextAttribute), false);
callContext.SayHi(..)
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class CallContextAttribute : Attribute
    {
        public void SayHi(string abc) { Console.WriteLine(abc); }
    }
    [CallContext]
    class WhereAreYouLocation
    {
        public void SayLocation()
        {
            this.GetType().GetCustomAttributes(false)[0].GetType().GetMethod("SayHi").Invoke(this.GetType().GetCustomAttributes(false)[0], new object[] { "123" });
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new WhereAreYouLocation().SayLocation();
        }
    }
}