C# Atrribute和反射的简单例子

Attribute 需要以Attribute 结尾, 并继承Attribute

namespace AttributeTest
{
    public class HeroAttribute : Attribute
    {
    }
}

namespace AttributeTest
{
    public class SkillAttribute : Attribute
    {
    }
}

namespace AttributeTest
{
    [Hero]
    public class Blademaster
    {
        [Skill]
        public void JiFengBu()
        {
            Console.WriteLine("疾风步");
        }
        [Skill]
        public void ZhiMingYiJi()
        {
            Console.WriteLine("致命一击");
        }
    }
}



using AttributeTest;
using System.Reflection;

List<Type> heroTypes = new();
object selecthero;

//所有英雄的类型
heroTypes = Assembly.GetExecutingAssembly().GetTypes()
    .Where(t => t.GetCustomAttributes(typeof(HeroAttribute), false).Any()).ToList();


//英雄的名字
var list = heroTypes.Select(t => t.Name).ToList();

foreach (var item in list)
{
    Console.WriteLine(item);
}

Console.WriteLine("==============");
foreach (var item in heroTypes)
{
    var t = Activator.CreateInstance(item);//创建对象
    var skillMethods = item.GetMethods().Where(m =>
    m.GetCustomAttributes(typeof(SkillAttribute), false)
    .Any()).ToList();

    var methodsName = skillMethods.Select(m => m.Name).ToList();
    methodsName.ForEach(x => Console.WriteLine(x));
}


结果 :

C# Atrribute和反射的简单例子_第1张图片

你可能感兴趣的:(c#,开发语言)