C# Attritube

特性学习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Oyster : System.Attribute
    {
        private string kind;
        public String Kind
        {
            get { return kind; }
            set { kind = value; }
        }
        private uint age;
        public uint Age
        {
            get { return age; }
            set { age = value; }
        }
        public Oyster(string arg)
        {
            this.Kind = arg;
        }

    }
    [Oyster("Thorny", Age = 3)]
    class Ship
    {
        [Oyster("Saddle")]
        public string Rudder;
        public string Kind { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            System.Reflection.MemberInfo memberInfo = typeof(Ship);
            System.Reflection.PropertyInfo propertyInfo = typeof(Ship).GetProperty("Age");
            Oyster hobbyStudent = (Oyster)Attribute.GetCustomAttribute(memberInfo, typeof(Oyster));
            Oyster hobbyName = (Oyster)Attribute.GetCustomAttribute(propertyInfo, typeof(Oyster));
            if (hobbyStudent != null)
            {
                Console.WriteLine("类Student的特性");
                Console.WriteLine("类名:{0}", memberInfo.Name);
                Console.WriteLine("兴趣类型:{0}", hobbyStudent.Kind);
                Console.WriteLine("兴趣年龄:{0}\n", hobbyStudent.Age);
            }
            if (hobbyName != null)
            {
                Console.WriteLine("属性Name的特性");
                Console.WriteLine("属性名:{0}", propertyInfo.Name);
                Console.WriteLine("兴趣类型:{0}", hobbyName.Kind);
                Console.WriteLine("兴趣年龄:{0}", hobbyName.Age);
            }
            Console.ReadKey();

        }
    }
}

可以试试吧,要求是Ship中必须要有特性类Oyster 中的属性之类的,这样才能进行很好的传递,即要有Kind和Age,要不会报空,

至于那个Rudder是自己随便加的扩展,就是可以外加,也可以不加。

关于main函数里面的那些调用,用到了反射的一些方法。

参考学习网站:

https://blog.csdn.net/FantasiaX/article/details/1627694 //特性 刘铁锰

https://blog.csdn.net/xiaouncle/article/details/70229119//特性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值