C#(反射\特性)
代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace AttributeClassApplication
{
class Program
{
static void Main(string[] args)
{
Type helpType = typeof(GetHelp);
//通过Type调用方法
MethodInfo methodInfoOK = helpType.GetMethod("HelpMe");
object obj = Activator.CreateInstance(helpType);
methodInfoOK.Invoke(obj,null);
//通过Type访问使用特性的对象
MethodInfo[] methodInfos = helpType.GetMethods();
Console.WriteLine("\n方法:");
foreach (MethodInfo methodInfo in methodInfos)
{
Console.WriteLine(methodInfo.Name);
}
//通过Type访问类使用的特性
Attribute[] attrs = Attribute.GetCustomAttributes(helpType);
foreach (Attribute attr in attrs)
{
if (attr is HelpAttribute)
{
HelpAttribute help = (HelpAttribute)attr;
Console.WriteLine(help.HelpInfo);
}
}
//访问方法使用的特性
Attribute attribute = Attribute.GetCustomAttribute(methodInfoOK, typeof(HelpAttribute));
HelpAttribute helpme = (HelpAttribute)attribute;
Console.WriteLine(helpme.HelpInfo);
Console.Read();
}
}
[Help("请帮一下我,我是你朋友!")]
public class GetHelp
{
[Help("我还需要你的帮助!")]
public void HelpMe()
{
Console.WriteLine("我听见有人要我帮忙,但不知道他是谁,也不知道要怎么做?");
}
}
[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class, AllowMultiple = true)]
public class HelpAttribute : Attribute
{
private string helpInfo;
public string HelpInfo
{
get { return helpInfo; }
set { helpInfo = value; }
}
public HelpAttribute(string helpInfo)
{
this.helpInfo = helpInfo;
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace AttributeClassApplication
{
class Program
{
static void Main(string[] args)
{
Type helpType = typeof(GetHelp);
//通过Type调用方法
MethodInfo methodInfoOK = helpType.GetMethod("HelpMe");
object obj = Activator.CreateInstance(helpType);
methodInfoOK.Invoke(obj,null);
//通过Type访问使用特性的对象
MethodInfo[] methodInfos = helpType.GetMethods();
Console.WriteLine("\n方法:");
foreach (MethodInfo methodInfo in methodInfos)
{
Console.WriteLine(methodInfo.Name);
}
//通过Type访问类使用的特性
Attribute[] attrs = Attribute.GetCustomAttributes(helpType);
foreach (Attribute attr in attrs)
{
if (attr is HelpAttribute)
{
HelpAttribute help = (HelpAttribute)attr;
Console.WriteLine(help.HelpInfo);
}
}
//访问方法使用的特性
Attribute attribute = Attribute.GetCustomAttribute(methodInfoOK, typeof(HelpAttribute));
HelpAttribute helpme = (HelpAttribute)attribute;
Console.WriteLine(helpme.HelpInfo);
Console.Read();
}
}
[Help("请帮一下我,我是你朋友!")]
public class GetHelp
{
[Help("我还需要你的帮助!")]
public void HelpMe()
{
Console.WriteLine("我听见有人要我帮忙,但不知道他是谁,也不知道要怎么做?");
}
}
[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class, AllowMultiple = true)]
public class HelpAttribute : Attribute
{
private string helpInfo;
public string HelpInfo
{
get { return helpInfo; }
set { helpInfo = value; }
}
public HelpAttribute(string helpInfo)
{
this.helpInfo = helpInfo;
}
}
}