特性學習
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//特性