什麼是屬性類?
從抽象類System.Attribute派生出來的類(無論是直接的還是間接的)都稱為屬性類(MSDN中的定義)。
屬性類的名稱一般都帶有Attribute字尾,但使用的時候可以包含也可以忽略,如果你自己起的名字沒有這個字尾,則需要全稱來區分了。如果不怕輸入麻煩,建議還是不管是否有字尾,都輸入全稱為好,這樣可以減少歧義。
在.NET架構中差不多定義了200個Attribute相關類,可見Attribute的應用十分廣泛,它的全圖在MSDN中如下:

System.Object

System.Attribute

System.AttributeUsageAttribute

System.CLSCompliantAttribute

System.ComponentModel.AmbientValueAttribute

System.ComponentModel.BindableAttribute

System.ComponentModel.BrowsableAttribute

System.ComponentModel.CategoryAttribute

System.ComponentModel.DefaultEventAttribute

System.ComponentModel.DefaultPropertyAttribute

System.ComponentModel.DefaultValueAttribute

System.ComponentModel.DescriptionAttribute

System.ComponentModel.Design.Serialization.DesignerSerializerAttribute

System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute

System.ComponentModel.DesignerAttribute

System.ComponentModel.DesignerCategoryAttribute

System.ComponentModel.DesignerSerializationVisibilityAttribute

System.ComponentModel.DesignOnlyAttribute

System.ComponentModel.DesignTimeVisibleAttribute

System.ComponentModel.EditorAttribute

System.ComponentModel.EditorBrowsableAttribute

System.ComponentModel.ImmutableObjectAttribute

System.ComponentModel.InheritanceAttribute

System.ComponentModel.InstallerTypeAttribute

System.ComponentModel.LicenseProviderAttribute

System.ComponentModel.ListBindableAttribute

System.ComponentModel.LocalizableAttribute

System.ComponentModel.MergablePropertyAttribute

System.ComponentModel.NotifyParentPropertyAttribute

System.ComponentModel.ParenthesizePropertyNameAttribute

System.ComponentModel.PropertyTabAttribute

System.ComponentModel.ProvidePropertyAttribute

System.ComponentModel.ReadOnlyAttribute

System.ComponentModel.RecommendedAsConfigurableAttribute

System.ComponentModel.RefreshPropertiesAttribute

System.ComponentModel.RunInstallerAttribute

System.ComponentModel.ToolboxItemAttribute

System.ComponentModel.ToolboxItemFilterAttribute

System.ComponentModel.TypeConverterAttribute

System.ContextStaticAttribute

System.Diagnostics.ConditionalAttribute

System.Diagnostics.DebuggableAttribute

System.Diagnostics.DebuggerHiddenAttribute

System.Diagnostics.DebuggerStepThroughAttribute

System.Drawing.ToolboxBitmapAttribute

System.EnterpriseServices.ApplicationAccessControlAttribute

System.EnterpriseServices.ApplicationActivationAttribute

System.EnterpriseServices.ApplicationIDAttribute

System.EnterpriseServices.ApplicationNameAttribute

System.EnterpriseServices.ApplicationQueuingAttribute

System.EnterpriseServices.AutoCompleteAttribute

System.EnterpriseServices.CompensatingResourceManager.ApplicationCrmEnabledAttribute

System.EnterpriseServices.ComponentAccessControlAttribute

System.EnterpriseServices.COMTIIntrinsicsAttribute

System.EnterpriseServices.ConstructionEnabledAttribute

System.EnterpriseServices.DescriptionAttribute

System.EnterpriseServices.EventClassAttribute

System.EnterpriseServices.EventTrackingEnabledAttribute

System.EnterpriseServices.ExceptionClassAttribute

System.EnterpriseServices.IISIntrinsicsAttribute

System.EnterpriseServices.InterfaceQueuingAttribute

System.EnterpriseServices.JustInTimeActivationAttribute

System.EnterpriseServices.LoadBalancingSupportedAttribute

System.EnterpriseServices.MustRunInClientContextAttribute

System.EnterpriseServices.ObjectPoolingAttribute

System.EnterpriseServices.PrivateComponentAttribute

System.EnterpriseServices.SecureMethodAttribute

System.EnterpriseServices.SecurityRoleAttribute

System.EnterpriseServices.SynchronizationAttribute

System.EnterpriseServices.TransactionAttribute

System.FlagsAttribute

System.LoaderOptimizationAttribute

System.Management.Instrumentation.IgnoreMemberAttribute

System.Management.Instrumentation.InstrumentationClassAttribute

System.Management.Instrumentation.InstrumentedAttribute

System.Management.Instrumentation.ManagedNameAttribute

System.MTAThreadAttribute

System.NonSerializedAttribute

System.ObsoleteAttribute

System.ParamArrayAttribute

System.Reflection.AssemblyAlgorithmIdAttribute

System.Reflection.AssemblyCompanyAttribute

System.Reflection.AssemblyConfigurationAttribute

System.Reflection.AssemblyCopyrightAttribute

System.Reflection.AssemblyCultureAttribute

System.Reflection.AssemblyDefaultAliasAttribute

System.Reflection.AssemblyDelaySignAttribute

System.Reflection.AssemblyDescriptionAttribute

System.Reflection.AssemblyFileVersionAttribute

System.Reflection.AssemblyFlagsAttribute

System.Reflection.AssemblyInformationalVersionAttribute

System.Reflection.AssemblyKeyFileAttribute

System.Reflection.AssemblyKeyNameAttribute

System.Reflection.AssemblyProductAttribute

System.Reflection.AssemblyTitleAttribute

System.Reflection.AssemblyTrademarkAttribute

System.Reflection.AssemblyVersionAttribute

System.Reflection.DefaultMemberAttribute

System.Resources.NeutralResourcesLanguageAttribute

System.Resources.SatelliteContractVersionAttribute

System.Runtime.CompilerServices.AccessedThroughPropertyAttribute

System.Runtime.CompilerServices.CompilationRelaxationsAttribute

System.Runtime.CompilerServices.CompilerGlobalScopeAttribute

System.Runtime.CompilerServices.CustomConstantAttribute

System.Runtime.CompilerServices.DecimalConstantAttribute

System.Runtime.CompilerServices.DiscardableAttribute

System.Runtime.CompilerServices.IndexerNameAttribute

System.Runtime.CompilerServices.MethodImplAttribute

System.Runtime.CompilerServices.RequiredAttributeAttribute

System.Runtime.InteropServices.AutomationProxyAttribute

System.Runtime.InteropServices.BestFitMappingAttribute

System.Runtime.InteropServices.ClassInterfaceAttribute

System.Runtime.InteropServices.CoClassAttribute

System.Runtime.InteropServices.ComAliasNameAttribute

System.Runtime.InteropServices.ComCompatibleVersionAttribute

System.Runtime.InteropServices.ComConversionLossAttribute

System.Runtime.InteropServices.ComEventInterfaceAttribute

System.Runtime.InteropServices.ComImportAttribute

System.Runtime.InteropServices.ComRegisterFunctionAttribute

System.Runtime.InteropServices.ComSourceInterfacesAttribute

System.Runtime.InteropServices.ComUnregisterFunctionAttribute

System.Runtime.InteropServices.ComVisibleAttribute

System.Runtime.InteropServices.DispIdAttribute

System.Runtime.InteropServices.DllImportAttribute

System.Runtime.InteropServices.FieldOffsetAttribute

System.Runtime.InteropServices.GuidAttribute

System.Runtime.InteropServices.IDispatchImplAttribute

System.Runtime.InteropServices.ImportedFromTypeLibAttribute

System.Runtime.InteropServices.InAttribute

System.Runtime.InteropServices.InterfaceTypeAttribute

System.Runtime.InteropServices.LCIDConversionAttribute

System.Runtime.InteropServices.MarshalAsAttribute

System.Runtime.InteropServices.OptionalAttribute

System.Runtime.InteropServices.OutAttribute

System.Runtime.InteropServices.PreserveSigAttribute

System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute

System.Runtime.InteropServices.ProgIdAttribute

System.Runtime.InteropServices.StructLayoutAttribute

System.Runtime.InteropServices.TypeLibFuncAttribute

System.Runtime.InteropServices.TypeLibTypeAttribute

System.Runtime.InteropServices.TypeLibVarAttribute

System.Runtime.InteropServices.TypeLibVersionAttribute

System.Runtime.Remoting.Messaging.OneWayAttribute

System.Runtime.Remoting.Metadata.SoapAttribute

System.Runtime.Remoting.Proxies.ProxyAttribute

System.Security.AllowPartiallyTrustedCallersAttribute

System.Security.Permissions.SecurityAttribute

System.Security.SuppressUnmanagedCodeSecurityAttribute

System.Security.UnverifiableCodeAttribute

System.SerializableAttribute

System.STAThreadAttribute

System.ThreadStaticAttribute

System.Web.Services.Configuration.XmlFormatExtensionAttribute

System.Web.Services.Configuration.XmlFormatExtensionPointAttribute

System.Web.Services.Configuration.XmlFormatExtensionPrefixAttribute

System.Web.Services.Protocols.HttpMethodAttribute

System.Web.Services.Protocols.MatchAttribute

System.Web.Services.Protocols.SoapDocumentMethodAttribute

System.Web.Services.Protocols.SoapDocumentServiceAttribute

System.Web.Services.Protocols.SoapExtensionAttribute

System.Web.Services.Protocols.SoapHeaderAttribute

System.Web.Services.Protocols.SoapRpcMethodAttribute

System.Web.Services.Protocols.SoapRpcServiceAttribute

System.Web.Services.WebMethodAttribute

System.Web.Services.WebServiceAttribute

System.Web.Services.WebServiceBindingAttribute

System.Web.UI.ConstructorNeedsTagAttribute

System.Web.UI.ControlBuilderAttribute

System.Web.UI.DataBindingHandlerAttribute

System.Web.UI.ParseChildrenAttribute

System.Web.UI.PartialCachingAttribute

System.Web.UI.PersistChildrenAttribute

System.Web.UI.PersistenceModeAttribute

System.Web.UI.TagPrefixAttribute

System.Web.UI.TemplateContainerAttribute

System.Web.UI.ToolboxDataAttribute

System.Web.UI.ValidationPropertyAttribute

System.Xml.Serialization.SoapAttributeAttribute

System.Xml.Serialization.SoapElementAttribute

System.Xml.Serialization.SoapEnumAttribute

System.Xml.Serialization.SoapIgnoreAttribute

System.Xml.Serialization.SoapIncludeAttribute

System.Xml.Serialization.SoapTypeAttribute

System.Xml.Serialization.XmlAnyAttributeAttribute

System.Xml.Serialization.XmlAnyElementAttribute

System.Xml.Serialization.XmlArrayAttribute

System.Xml.Serialization.XmlArrayItemAttribute

System.Xml.Serialization.XmlAttributeAttribute

System.Xml.Serialization.XmlChoiceIdentifierAttribute

System.Xml.Serialization.XmlElementAttribute

System.Xml.Serialization.XmlEnumAttribute

System.Xml.Serialization.XmlIgnoreAttribute

System.Xml.Serialization.XmlIncludeAttribute

System.Xml.Serialization.XmlNamespaceDeclarationsAttribute

System.Xml.Serialization.XmlRootAttribute

System.Xml.Serialization.XmlTextAttribute

System.Xml.Serialization.XmlTypeAttribute
System.STAThreadAttribute
大家在一般使用中會留意到這個屬性嗎?用VS.NET建立一個項目,往往在main前面會如下面所示:
/// <summary>
/// 應用程式的主入口點。
/// </summary>

[STAThread]

static void Main()
{
Application.Run(new frmMain());
}
其實這個就是屬性類STAThreadAttribute了,它的作用表示應用程式的COM線程模型是單線程單元(STA)。
屬性類的實用性:
1.利用XML相關的屬性類,将相關業務類XML序列化,可以達到儲存狀态和遠端傳輸交換類資訊等作用。
共14個和XML相關的屬性類:
System.Xml.Serialization.XmlAnyAttributeAttribute
System.Xml.Serialization.XmlAnyElementAttribute
System.Xml.Serialization.XmlArrayAttribute
System.Xml.Serialization.XmlArrayItemAttribute
System.Xml.Serialization.XmlAttributeAttribute
System.Xml.Serialization.XmlChoiceIdentifierAttribute
System.Xml.Serialization.XmlElementAttribute
System.Xml.Serialization.XmlEnumAttribute
System.Xml.Serialization.XmlIgnoreAttribute
System.Xml.Serialization.XmlIncludeAttribute
System.Xml.Serialization.XmlNamespaceDeclarationsAttribute
System.Xml.Serialization.XmlRootAttribute
System.Xml.Serialization.XmlTextAttribute
System.Xml.Serialization.XmlTypeAttribute
最近做一個項目,需要将一些界面輸入的有一定結構規律的資訊儲存起來,然後下次需要時候可以調入到對應的界面位置上使用。(其實這個是很多應用都會碰到的)。結構和UI的對應關系可能會經常變動的,而且結構中需要填寫的内容不是所有都必須的,直接用關系型資料庫來儲存似乎不是太好的方案。首先想到就是用XML檔案來儲存這些資訊了,而界面之間的資訊顯示是有關聯的,可以說需要一個緩沖來記錄這些資訊,想到的就是定義一個類來記錄和操作這些資訊。這自然遇到一個問題,如何保持類和XML資料的同步呢?
生成的XML檔案需要給其它業務來做處理,格式上有一定的規範,對于類來說,資訊都儲存在字段或者屬性那裡的,并沒有差別,但XML中可能有些資訊是Attribute,有些又是Element的。如何靈活地處理這些關系呢?用與XML相關的屬性來定義這些字段和類就可以了。
(1) 類資訊序列化到XML檔案中的代碼

public void SerializeObject(string filename)
XmlSerializer s = new XmlSerializer(typeof(Tables));
TextWriter writer = new StreamWriter(filename);
Tables group = new Tables();
group.GroupID = 10.089f;
group.IsActive = false;
group.HexBytes = new byte[1]{Convert.ToByte(100)};
Employee x = new Employee();
Employee y = new Employee();
x.Name = "Jack";
y.Name = "Jill";
x.des2 = "Yyyy
";
x.colType = new ColumnType[2];
x.colType[0] = new ColumnType();
x.colType[1] = new ColumnType();
x.colType[0].linkField = "Haaa
x.colType[1].linkType = "Zzzz
y.Age[0] = 20;
y.Age[1] = 40;
y.Desc = "OK";
group.Employees = new Employee[2]{x,y};
Manager mgr = new Manager();
mgr.Name = "Sara";
mgr.Level = 4;
mgr.Desc = "Yes";
mgr.aHead = true;
group.Manager = mgr;
group.ExtraInfo = new ArrayList();
group.ExtraInfo.Add(42);
group.ExtraInfo.Add("Answer");
s.Serialize(writer, group);
writer.Close();

(2) XML檔案資訊變成類的資訊的代碼

public void DeserializeObject(string filename)
FileStream fs = new FileStream(filename, FileMode.Open);
XmlSerializer x = new XmlSerializer(typeof(Tables));
Tables g = (Tables) x.Deserialize(fs);
int i=0;
foreach(Employee e in g.Employees)
{
i = i + 1;
Console.WriteLine("No {0} Name: {1}",i.ToString(),e.Name);
}
Console.WriteLine(g.Manager.Name);
Console.WriteLine(g.GroupID);
Console.WriteLine(g.HexBytes[0]);
(3)例子中相關類資訊生成的XML檔案

<?xml version="1.0" encoding="utf-8"?>

<Tables xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<Member>

<Employee AHead="false">

<Name>Jack</Name>

<Age>0</Age>


<des2>Yyyy
</des2>

<ColumnType LinkField="Haaa
" />

<ColumnType LinkType="Zzzz

</Employee>

<Employee Desc="OK" AHead="false">

<Name>Jill</Name>

<Age>20</Age>

<Age>40</Age>


</Member>

<Building>10.088999748229981</Building>

<HexBytes>64</HexBytes>

<IsActive>false</IsActive>

<Manager Desc="Yes" AHead="true">

<Name>Sara</Name>

<Age>0</Age>


<Level>4</Level>

</Manager>

<ObjectNumber>42</ObjectNumber>

<ObjectString>Answer</ObjectString>

</Tables>
(4) XML總體架構如何用XML相關屬性類描述

public class Tables
{
[XmlArray(ElementName = "Member")]
public Employee[] Employees;
[XmlElement(DataType = "double",
ElementName = "Building")]
public double GroupID;
[XmlElement(DataType = "hexBinary")]
public byte [] HexBytes;
[XmlElement(DataType = "boolean")]
public bool IsActive;
[XmlElement(Type = typeof(Manager))]
public Employee Manager;
[XmlElement(typeof(int),
ElementName = "ObjectNumber"),
XmlElement(typeof(string),
ElementName = "ObjectString")]
public ArrayList ExtraInfo;
}

(5) 類的字段資訊表示為屬性的方法

public class Employee
public string Name;
[XmlElement(typeof(int))]
public int[] Age = new int[2];
[XmlAttribute(AttributeName = "Desc")]
public string Desc;
[XmlAttribute(AttributeName = "AHead")]
public bool aHead;
public string des2;
[XmlElement(ElementName="ColumnType")]
public ColumnType[] colType;
}

2.自己根據需要定義自己的屬性類,例如定義相關業務類和UI的關系。
在使用中,資訊不是一個UI就完成的,可能經過了幾個UI,或者幾個頁面去互動,但可能業務的調整,顯示的位置或者一些參數可能需要調整的,這些UI的資訊能否也定義為類的某些屬性?
從.NET的Attribute派生一個客戶定制類可以輕松做到這點,定制類隻需要從System.Attribute派生即可。

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Class,AllowMultiple=true)]

public class LayoutAttribute : Attribute
string m_desc;
public string OwnPage;
public string GetDesc()
return m_desc;
public LayoutAttribute(string strDesc)
m_desc = strDesc;

AttributeUsage這個類定義了LayoutAttribute的一些基本資訊,例如這裡定義了LayoutAttribute适用于字段,類,并且允許重複定義的。
在應用中,可以利用反射機制,将這些定義的資訊擷取,進而判斷應該在界面上如何處理了。

Type myType = Type.GetType("testXmlAttr.Manager");

Console.WriteLine(myType.FullName);

FieldInfo myFieldInfo = myType.GetField("Level");


object[] atts = myFieldInfo.GetCustomAttributes(false);

for (int i=0;i<atts.Length;i++)

Console.WriteLine(((LayoutAttribute)atts[i]).OwnPage);

例子運作結果:(同時在目前目錄下生成testXmlAttr.xml)
本文轉自風前絮~~部落格園部落格,原文連結:http://www.cnblogs.com/windsails/archive/2004/09/08/41006.html,如需轉載請自行聯系原作者