class1.cs

来自「C#开发教程 由浅入深 配有实例 是初学者的好帮手」· CS 代码 · 共 61 行

CS
61
字号
using System;
using System.Reflection;

namespace AttribInheritance
{
	[AttributeUsage(
		 AttributeTargets.All, 
		 AllowMultiple=true,
//		 AllowMultiple=false,
		 Inherited=true
	)]
	public class SomethingAttribute : Attribute
	{
		private string name;
		public string Name
		{ 
			get { return name; }
			set { name = value; }
		}

		public SomethingAttribute(string str)
		{
			this.name = str;
		}
	}
		
	[Something("abc")]
	class MyClass
	{
	}

	[Something("def")]
	class Another : MyClass
	{
	}
		
	class Test
	{
		[STAThread]
		static void Main(string[] args)
		{
			Type type = 
				Type.GetType("AttribInheritance.Another");
			foreach (Attribute attr in 
				type.GetCustomAttributes(true))
//				type.GetCustomAttributes(false))
			{
				SomethingAttribute sa = 
					attr as SomethingAttribute;
				if (null != sa)
				{
    				Console.WriteLine(
						"Custom Attribute: {0}", 
						sa.Name);
				}
			}

		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?