读书人

调用Attribute的步骤

发布时间: 2013-10-18 20:53:13 作者: rapoo

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

读书人网 >C#

热点推荐