前段时间园子有个人发一道面试题是这样的,找出.net framework 中的所有Attribute。通常这个问题需要指定范围的,下面让我们来实现一下查找当前AppDomain中程序集的所有Attribute,您可以举一反三,接下看下来的代码:
1: [TestMethod]
2: public void TestGetCurrentAppDomainAttribuesNameTree()
3: {
4: // Recursively build the class hierarchy as a hyphen-separated string
5: Func<Type, String> classNameAndBase = null;
6: classNameAndBase = t => string.Format("-{0}{1}", t.FullName,
7: ((t.BaseType != typeof(Object)) ? classNameAndBase(t.BaseType) : String.Empty));
8:
9: // Define our query to find all the public Attribute-derived types in this Current AppDomain's assemblies
10: var attributeTree =
11: (from a in AppDomain.CurrentDomain.GetAssemblies()
12: from t in a.GetExportedTypes()
13: where t.IsClass && t.IsPublic && typeof(Attribute).IsAssignableFrom(t)
14: let typeHierarchyTemp = classNameAndBase(t).Split('-').Reverse().ToArray()
15: let typeHierarchy = string.Join("-", typeHierarchyTemp, 0, typeHierarchyTemp.Length - 1)
16: orderby typeHierarchy
17: select typeHierarchy).ToArray();
18:
19: // Display the Attribute tree
20: Console.WriteLine(@"{0} Attribute types found.", attributeTree.Length);
21: foreach (var x in attributeTree.Select(s => s.Split('-')))
22: {
23: // Indent based on # of base types and show the most-derived type
24: Console.WriteLine(new String(' ', 3 * (x.Length - 1)) + x[x.Length - 1]);
25: }
26: }
注意第6行我们使用基于Func<T,Result>的递归,您可以参考以前的文章。 第11行代码我们是基于当前的AppDomain,您可以修改你的目标Assembiles。代码中注释您应该可以看懂。此时,我的开发环境输出这样的结果:
366 Attribute types found.
System.Attribute
Microsoft.SqlServer.Server.SqlFacetAttribute
Microsoft.SqlServer.Server.SqlFunctionAttribute
Microsoft.SqlServer.Server.SqlMethodAttribute
Microsoft.SqlServer.Server.SqlProcedureAttribute
Microsoft.SqlServer.Server.SqlTriggerAttribute
Microsoft.SqlServer.Server.SqlUserDefinedAggregateAttribute
Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute
Microsoft.VisualStudio.TestTools.Common.GroupingPropertyAttribute
Microsoft.VisualStudio.TestTools.Common.NonPersistableAttribute
Microsoft.VisualStudio.TestTools.Common.PersistenceElementNameAttribute
Microsoft.VisualStudio.TestTools.Common.PropertyWindowAttribute
Microsoft.VisualStudio.TestTools.Common.VisiblePropertyAttribute
Microsoft.VisualStudio.TestTools.Common.UserVisiblePropertyAttribute
Microsoft.VisualStudio.TestTools.Execution.DataCollectorConfigurationEditorAttribute
Microsoft.VisualStudio.TestTools.Execution.DataCollectorConfigurationEditorTypeUriAttribute
Microsoft.VisualStudio.TestTools.Execution.DataCollectorDescriptionAttribute
Microsoft.VisualStudio.TestTools.Execution.DataCollectorEnabledByDefaultAttribute
Microsoft.VisualStudio.TestTools.Execution.DataCollectorFriendlyNameAttribute
Microsoft.VisualStudio.TestTools.Execution.DataCollectorTypeUriAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.AssemblyCleanupAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.AssemblyInitializeAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.CssIterationAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.CssProjectStructureAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.DeploymentItemAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionBaseAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.HostTypeAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.IgnoreAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.OwnerAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.PriorityAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.ShadowingAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryBaseAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.TestClassExtensionAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.TimeoutAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.Web.AspNetDevelopmentServerAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.Web.AspNetDevelopmentServerHostAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.Web.CredentialAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.Web.UrlToTestAttribute
Microsoft.VisualStudio.TestTools.UnitTesting.WorkItemAttribute
System.AttributeUsageAttribute
System.CLSCompliantAttribute
System.CodeDom.Compiler.GeneratedCodeAttribute
System.ComponentModel.AmbientValueAttribute
System.ComponentModel.AttributeProviderAttribute
System.ComponentModel.BindableAttribute
System.ComponentModel.BrowsableAttribute
System.ComponentModel.CategoryAttribute
System.ComponentModel.ComplexBindingPropertiesAttribute
System.ComponentModel.DataObjectAttribute
System.ComponentModel.DataObjectFieldAttribute
System.ComponentModel.DataObjectMethodAttribute
System.ComponentModel.DefaultBindingPropertyAttribute
System.ComponentModel.DefaultEventAttribute
System.ComponentModel.DefaultPropertyAttribute
System.ComponentModel.DefaultValueAttribute
System.ComponentModel.DescriptionAttribute
Microsoft.VisualStudio.TestTools.Common.LocalizedDescriptionAttribute
System.Data.DataSysDescriptionAttribute
System.Diagnostics.MonitoringDescriptionAttribute
System.IO.IODescriptionAttribute
System.Timers.TimersDescriptionAttribute
System.ComponentModel.Design.HelpKeywordAttribute
System.ComponentModel.Design.Serialization.DefaultSerializationProviderAttribute
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.DisplayNameAttribute
Microsoft.VisualStudio.TestTools.Common.TestCaseManagementDisplayNameAttribute
System.ComponentModel.EditorAttribute
System.ComponentModel.EditorBrowsableAttribute
System.ComponentModel.ExtenderProvidedPropertyAttribute
System.ComponentModel.ImmutableObjectAttribute
System.ComponentModel.InheritanceAttribute
System.ComponentModel.InitializationEventAttribute
System.ComponentModel.InstallerTypeAttribute
System.ComponentModel.LicenseProviderAttribute
System.ComponentModel.ListBindableAttribute
System.ComponentModel.LocalizableAttribute
System.ComponentModel.LookupBindingPropertiesAttribute
System.ComponentModel.MergablePropertyAttribute
System.ComponentModel.NotifyParentPropertyAttribute
System.ComponentModel.ParenthesizePropertyNameAttribute
System.ComponentModel.PasswordPropertyTextAttribute
System.ComponentModel.PropertyTabAttribute
System.ComponentModel.ProvidePropertyAttribute
System.ComponentModel.ReadOnlyAttribute
System.ComponentModel.RecommendedAsConfigurableAttribute
System.ComponentModel.RefreshPropertiesAttribute
System.ComponentModel.RunInstallerAttribute
System.ComponentModel.SettingsBindableAttribute
System.ComponentModel.ToolboxItemAttribute
System.ComponentModel.ToolboxItemFilterAttribute
System.ComponentModel.TypeConverterAttribute
System.ComponentModel.TypeDescriptionProviderAttribute
System.Configuration.ConfigurationCollectionAttribute
System.Configuration.ConfigurationPropertyAttribute
System.Configuration.ConfigurationValidatorAttribute
System.Configuration.CallbackValidatorAttribute
System.Configuration.IntegerValidatorAttribute
System.Configuration.LongValidatorAttribute
System.Configuration.PositiveTimeSpanValidatorAttribute
System.Configuration.RegexStringValidatorAttribute
System.Configuration.StringValidatorAttribute
System.Configuration.SubclassTypeValidatorAttribute
System.Configuration.TimeSpanValidatorAttribute
System.Configuration.DefaultSettingValueAttribute
System.Configuration.NoSettingsVersionUpgradeAttribute
System.Configuration.SettingAttribute
System.Configuration.ApplicationScopedSettingAttribute
System.Configuration.UserScopedSettingAttribute
System.Configuration.SettingsDescriptionAttribute
System.Configuration.SettingsGroupDescriptionAttribute
System.Configuration.SettingsGroupNameAttribute
System.Configuration.SettingsManageabilityAttribute
System.Configuration.SettingsProviderAttribute
System.Configuration.SettingsSerializeAsAttribute
System.Configuration.SpecialSettingAttribute
System.ContextStaticAttribute
System.Data.Common.DbProviderSpecificTypePropertyAttribute
System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute
System.Diagnostics.CodeAnalysis.SuppressMessageAttribute
System.Diagnostics.ConditionalAttribute
System.Diagnostics.Contracts.ContractClassAttribute
System.Diagnostics.Contracts.ContractClassForAttribute
System.Diagnostics.Contracts.ContractInvariantMethodAttribute
System.Diagnostics.Contracts.ContractPublicPropertyNameAttribute
System.Diagnostics.Contracts.ContractReferenceAssemblyAttribute
System.Diagnostics.Contracts.ContractRuntimeIgnoredAttribute
System.Diagnostics.Contracts.ContractVerificationAttribute
System.Diagnostics.Contracts.PureAttribute
System.Diagnostics.DebuggableAttribute
System.Diagnostics.DebuggerBrowsableAttribute
System.Diagnostics.DebuggerDisplayAttribute
System.Diagnostics.DebuggerHiddenAttribute
System.Diagnostics.DebuggerNonUserCodeAttribute
System.Diagnostics.DebuggerStepperBoundaryAttribute
System.Diagnostics.DebuggerStepThroughAttribute
System.Diagnostics.DebuggerTypeProxyAttribute
System.Diagnostics.DebuggerVisualizerAttribute
System.Diagnostics.SwitchAttribute
System.Diagnostics.SwitchLevelAttribute
System.FlagsAttribute
System.LoaderOptimizationAttribute
System.Management.Instrumentation.ManagementEntityAttribute
System.Management.Instrumentation.ManagementMemberAttribute
System.Management.Instrumentation.ManagementCommitAttribute
System.Management.Instrumentation.ManagementConfigurationAttribute
System.Management.Instrumentation.ManagementKeyAttribute
System.Management.Instrumentation.ManagementNewInstanceAttribute
System.Management.Instrumentation.ManagementBindAttribute
System.Management.Instrumentation.ManagementCreateAttribute
System.Management.Instrumentation.ManagementEnumeratorAttribute
System.Management.Instrumentation.ManagementProbeAttribute
System.Management.Instrumentation.ManagementRemoveAttribute
System.Management.Instrumentation.ManagementTaskAttribute
System.Management.Instrumentation.ManagementNameAttribute
System.Management.Instrumentation.ManagementReferenceAttribute
System.Management.Instrumentation.WmiConfigurationAttribute
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.Reflection.ObfuscateAssemblyAttribute
System.Reflection.ObfuscationAttribute
System.Resources.NeutralResourcesLanguageAttribute
System.Resources.SatelliteContractVersionAttribute
System.Runtime.AssemblyTargetedPatchBandAttribute
System.Runtime.CompilerServices.AccessedThroughPropertyAttribute
System.Runtime.CompilerServices.CompilationRelaxationsAttribute
System.Runtime.CompilerServices.CompilerGeneratedAttribute
System.Runtime.CompilerServices.CompilerGlobalScopeAttribute
System.Runtime.CompilerServices.CustomConstantAttribute
System.Runtime.CompilerServices.DateTimeConstantAttribute
System.Runtime.CompilerServices.IDispatchConstantAttribute
System.Runtime.CompilerServices.IUnknownConstantAttribute
System.Runtime.CompilerServices.DecimalConstantAttribute
System.Runtime.CompilerServices.DefaultDependencyAttribute
System.Runtime.CompilerServices.DependencyAttribute
System.Runtime.CompilerServices.DiscardableAttribute
System.Runtime.CompilerServices.DynamicAttribute
System.Runtime.CompilerServices.ExtensionAttribute
System.Runtime.CompilerServices.FixedAddressValueTypeAttribute
System.Runtime.CompilerServices.FixedBufferAttribute
System.Runtime.CompilerServices.HasCopySemanticsAttribute
System.Runtime.CompilerServices.IndexerNameAttribute
System.Runtime.CompilerServices.InternalsVisibleToAttribute
System.Runtime.CompilerServices.MethodImplAttribute
System.Runtime.CompilerServices.NativeCppClassAttribute
System.Runtime.CompilerServices.ReferenceAssemblyAttribute
System.Runtime.CompilerServices.RequiredAttributeAttribute
System.Runtime.CompilerServices.RuntimeCompatibilityAttribute
System.Runtime.CompilerServices.ScopelessEnumAttribute
System.Runtime.CompilerServices.SpecialNameAttribute
System.Runtime.CompilerServices.StringFreezingAttribute
System.Runtime.CompilerServices.SuppressIldasmAttribute
System.Runtime.CompilerServices.TypeForwardedFromAttribute
System.Runtime.CompilerServices.TypeForwardedToAttribute
System.Runtime.CompilerServices.UnsafeValueTypeAttribute
System.Runtime.ConstrainedExecution.PrePrepareMethodAttribute
System.Runtime.ConstrainedExecution.ReliabilityContractAttribute
System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute
System.Runtime.InteropServices.AllowReversePInvokeCallsAttribute
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.ComDefaultInterfaceAttribute
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.DefaultCharSetAttribute
System.Runtime.InteropServices.DefaultParameterValueAttribute
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.ManagedToNativeComInteropStubAttribute
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.SetWin32ContextInIDispatchAttribute
System.Runtime.InteropServices.StructLayoutAttribute
System.Runtime.InteropServices.TypeIdentifierAttribute
System.Runtime.InteropServices.TypeLibFuncAttribute
System.Runtime.InteropServices.TypeLibImportClassAttribute
System.Runtime.InteropServices.TypeLibTypeAttribute
System.Runtime.InteropServices.TypeLibVarAttribute
System.Runtime.InteropServices.TypeLibVersionAttribute
System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute
System.Runtime.Remoting.Contexts.ContextAttribute
System.Runtime.Remoting.Activation.UrlAttribute
System.Runtime.Remoting.Contexts.SynchronizationAttribute
System.Runtime.Remoting.Messaging.OneWayAttribute
System.Runtime.Remoting.Metadata.SoapAttribute
System.Runtime.Remoting.Metadata.SoapFieldAttribute
System.Runtime.Remoting.Metadata.SoapMethodAttribute
System.Runtime.Remoting.Metadata.SoapParameterAttribute
System.Runtime.Remoting.Metadata.SoapTypeAttribute
System.Runtime.Remoting.Proxies.ProxyAttribute
System.Runtime.Serialization.OnDeserializedAttribute
System.Runtime.Serialization.OnDeserializingAttribute
System.Runtime.Serialization.OnSerializedAttribute
System.Runtime.Serialization.OnSerializingAttribute
System.Runtime.Serialization.OptionalFieldAttribute
System.Runtime.TargetedPatchingOptOutAttribute
System.Runtime.Versioning.ComponentGuaranteesAttribute
System.Runtime.Versioning.ResourceConsumptionAttribute
System.Runtime.Versioning.ResourceExposureAttribute
System.Runtime.Versioning.TargetFrameworkAttribute
System.Security.AllowPartiallyTrustedCallersAttribute
System.Security.Permissions.SecurityAttribute
System.Security.Permissions.CodeAccessSecurityAttribute
System.Configuration.ConfigurationPermissionAttribute
System.Data.Common.DBDataPermissionAttribute
System.Data.Odbc.OdbcPermissionAttribute
System.Data.OleDb.OleDbPermissionAttribute
System.Data.SqlClient.SqlClientPermissionAttribute
System.Diagnostics.EventLogPermissionAttribute
System.Diagnostics.PerformanceCounterPermissionAttribute
System.Net.DnsPermissionAttribute
System.Net.Mail.SmtpPermissionAttribute
System.Net.NetworkInformation.NetworkInformationPermissionAttribute
System.Net.SocketPermissionAttribute
System.Net.WebPermissionAttribute
System.Security.Permissions.EnvironmentPermissionAttribute
System.Security.Permissions.FileDialogPermissionAttribute
System.Security.Permissions.FileIOPermissionAttribute
System.Security.Permissions.GacIdentityPermissionAttribute
System.Security.Permissions.HostProtectionAttribute
System.Security.Permissions.IsolatedStoragePermissionAttribute
System.Security.Permissions.IsolatedStorageFilePermissionAttribute
System.Security.Permissions.KeyContainerPermissionAttribute
System.Security.Permissions.PermissionSetAttribute
System.Security.Permissions.PrincipalPermissionAttribute
System.Security.Permissions.PublisherIdentityPermissionAttribute
System.Security.Permissions.ReflectionPermissionAttribute
System.Security.Permissions.RegistryPermissionAttribute
System.Security.Permissions.SecurityPermissionAttribute
System.Security.Permissions.SiteIdentityPermissionAttribute
System.Security.Permissions.StorePermissionAttribute
System.Security.Permissions.StrongNameIdentityPermissionAttribute
System.Security.Permissions.TypeDescriptorPermissionAttribute
System.Security.Permissions.UIPermissionAttribute
System.Security.Permissions.UrlIdentityPermissionAttribute
System.Security.Permissions.ZoneIdentityPermissionAttribute
System.Web.AspNetHostingPermissionAttribute
System.Security.SecurityCriticalAttribute
System.Security.SecurityRulesAttribute
System.Security.SecuritySafeCriticalAttribute
System.Security.SecurityTransparentAttribute
System.Security.SecurityTreatAsSafeAttribute
System.Security.SuppressUnmanagedCodeSecurityAttribute
System.Security.UnverifiableCodeAttribute
System.SerializableAttribute
System.STAThreadAttribute
System.ThreadStaticAttribute
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.XmlSchemaProviderAttribute
System.Xml.Serialization.XmlSerializerAssemblyAttribute
System.Xml.Serialization.XmlSerializerVersionAttribute
System.Xml.Serialization.XmlTextAttribute
System.Xml.Serialization.XmlTypeAttribute
希望这篇POST能给你带来开发上的乐趣!
作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog。