特性学习
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//特性