元数据(二)

此博客展示了一段C#代码,通过反射获取自定义特性中的颜色元数据。定义了Color特性类,为Animal、Cat、Dog类添加颜色特性,在Main方法中获取并输出这些类的颜色信息,体现了元数据在C#编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;

namespace ConsoleApplication2
{
 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
 class Class1
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
   System.Reflection.MemberInfo info=typeof(Cat);
   Color colorA = (Color)Attribute.GetCustomAttribute(info,typeof(Color));
   if(colorA!=null)
   {
    Console.WriteLine("color of cat is:{0}",colorA.color);
    
   }

   
   info=typeof(Animal);
   colorA = (Color)Attribute.GetCustomAttribute(info,typeof(Color));
   if(colorA!=null)
   {
    Console.WriteLine("color of animal is:{0}",colorA.color);
    
   }

  }
 }
 
 [AttributeUsage(AttributeTargets.Class)]
 public class Color : Attribute{
  public string color;
  public Color(string color){
   this.color=color;
  }

 }

 [Color("red")]
 public class Animal
 {
 
 }

 [Color("blue")]
 public class Cat:Animal
 {
 
 }
 
 [Color("yellow")]
 public class Dog:Animal
 {
 
 }

}

这里的东西是这样的意思,有一个元数据,叫做颜色。

有一个东西叫做动物,她的颜色是红色的。

动物中有一种叫做猫,他是蓝色的。

有一种叫做狗,他是黄色的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值