首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

调用Attribute的步骤

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

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

热点排行