CSharp 之 Attribute

前言

本篇文章旨在认识C# 中的特性,知道什么是特性,特性的作用,如何使用特性,如何自定义特性

什么是特性

特性即Attribute,可以宣告式地为自己的代码添加注解来实现某些特殊的功能。 它们的把一些附加的信息同目标关联起来,这个目标可以是类,可以是方法,可以是枚举,等等。编译器检查到代码中的特性后,会为其生成对应的元数据。

在.Net的类库中提供了非常多的特性例如比较常见的

[DllImport] 、[Serializable] 、[StructLayout]

    
如何使用特性

使用方括号,把特性名括起来放到应用的目标前方,特性类名后缀“Attribute”可以省略,例如:

[DllImport("MyLib", CharSet=CharSet.Auto, SetLastError=true)]
public static extern string GetVersion();

如果没有参数则不需要写括号。

特性的本质

特性其实就是一个类的实例,因此需要这个类至少拥有一个公共的构造函数。这个类要派生自System.Attribute

定义自己的特性类

可以把特性想像成一个逻辑状态容器,不需要很复杂,只需要一个公共构造器来接收特性的强制性(或定位性)状态信息,可提供公共字段或属性以接收特性的可选状态信息。类不应提供任何公共方法、事件或其他成员。

实际测试代码:

 如果把默认构造器私有化则会报上面的错误

设定特性的合法使用范围

告诉编译器,这个某个特性只能给某个或几个类型元素使用, 例如只能应用于Class和Method,这个时候就需要使用AttributeUsageAttribute了,这个特性作用于我们自定义的特性类,即可限制我们的自定义类的使用范围。

它有三个参数:1.目标类型(AttributeTarget) 2.是否支持重复(AllowMultiple) 3.是否可被子类继承(Inherited)

AttributeTargets是一个位标志枚举类型,见下方代码:

/// <summary>Specifies the application elements on which it is valid to apply an attribute.</summary>
  [Flags]
  [ComVisible(true)]
  [__DynamicallyInvokable]
  [Serializable]
  public enum AttributeTargets
  {
    /// <summary>Attribute can be applied to an assembly.</summary>
    [__DynamicallyInvokable] Assembly = 1,
    /// <summary>Attribute can be applied to a module.</summary>
    [__DynamicallyInvokable] Module = 2,
    /// <summary>Attribute can be applied to a class.</summary>
    [__DynamicallyInvokable] Class = 4,
    /// <summary>Attribute can be applied to a structure; that is, a value type.</summary>
    [__DynamicallyInvokable] Struct = 8,
    /// <summary>Attribute can be applied to an enumeration.</summary>
    [__DynamicallyInvokable] Enum = 16, // 0x00000010
    /// <summary>Attribute can be applied to a constructor.</summary>
    [__DynamicallyInvokable] Constructor = 32, // 0x00000020
    /// <summary>Attribute can be applied to a method.</summary>
    [__DynamicallyInvokable] Method = 64, // 0x00000040
    /// <summary>Attribute can be applied to a property.</summary>
    [__DynamicallyInvokable] Property = 128, // 0x00000080
    /// <summary>Attribute can be applied to a field.</summary>
    [__DynamicallyInvokable] Field = 256, // 0x00000100
    /// <summary>Attribute can be applied to an event.</summary>
    [__DynamicallyInvokable] Event = 512, // 0x00000200
    /// <summary>Attribute can be applied to an interface.</summary>
    [__DynamicallyInvokable] Interface = 1024, // 0x00000400
    /// <summary>Attribute can be applied to a parameter.</summary>
    [__DynamicallyInvokable] Parameter = 2048, // 0x00000800
    /// <summary>Attribute can be applied to a delegate.</summary>
    [__DynamicallyInvokable] Delegate = 4096, // 0x00001000
    /// <summary>Attribute can be applied to a return value.</summary>
    [__DynamicallyInvokable] ReturnValue = 8192, // 0x00002000
    /// <summary>Attribute can be applied to a generic parameter.</summary>
    [__DynamicallyInvokable] GenericParameter = 16384, // 0x00004000
    /// <summary>Attribute can be applied to any application element.</summary>
    [__DynamicallyInvokable] All = GenericParameter | ReturnValue | Delegate | Parameter | Interface | Event | Field | Property | Method | Constructor | Enum | Struct | Class | Module | Assembly, // 0x00007FFF
  }

AllowMultiple如果不为true,那么对于同一个目标,一个特性只能应用一次

Inherited如果是true,则会将特性应用于派生类和重写的方法

如果我们不给自定义特性添加AttributeUsage,则默认为针对所有目标元素都可以使用该特性。

让特性活起来

检测定制特性

光定义特性没用,还要定义这些特性的处理逻辑,这免不了要解决一个问题就是如何发现目标身上的特性,我们可以通过反射来实现。

System.Reflection.CustomAttributeExtensions

有三个静态方法:IsDefined、GetCustomAttributes、GetCustomAttribute

 

 后两个还支持泛型获取:

 如果只想判断某个目标是否应用了某个特性,则使用IsDefined是最优解,但如果要构造特性对象,则需要使用后面两个了。每次调用GetCustomAttribute和GetCustomAttributes的时候都会构造指定特性类型的实例,并根据源代码中的指定值来设置特性的属性。

System.Reflection定义了几个类允许检查模块的元数据,包括Assembly、Module、ParameterInfo、MemberInfo、Type、MethodInfo、ConstructorInfo、FieldInfo、EventInfo、PropertyInfo以及其各自的*Builder类,这些类都提供了IsDefined和GetCustomAttributes方法。

参考书籍:CLR via C# 第4版

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
This new 7th edition of Pro C# 6.0 and the .NET 4.6 Platform has been completely revised and rewritten to reflect the latest changes to the C# language specification and new advances in the .NET Framework. You'll find new chapters covering all the important new features that make .NET 4.6 the most comprehensive release yet, including: A Refined ADO.NET Entity Framework Programming Model Numerous IDE and MVVM Enhancements for WPF Desktop Development Numerous updates to the ASP.NET Web APIs This comes on top of award winning coverage of core C# features, both old and new, that have made the previous editions of this book so popular. Readers will gain a solid foundation of object-oriented development techniques, attributes and reflection, generics and collections as well as numerous advanced topics not found in other texts (such as CIL opcodes and emitting dynamic assemblies). The mission of this book is to provide you with a comprehensive foundation in the C# programming language and the core aspects of the .NET platform plus overviews of technologies built on top of C# and .NET (ADO.NET and Entity Framework, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), ASP.NET (WebForms, MVC, WebAPI).). Once you digest the information presented in these chapters, you’ll be in a perfect position to apply this knowledge to your specific programming assignments, and you’ll be well equipped to explore the .NET universe on your own terms. What you’ll learn Be the first to understand the .NET 4.6 platform and C# 6. Discover the ins and outs of the leading .NET technology. Learn from an award-winning author who has been teaching the .NET world since version 1.0. Find complete coverage of XAML, .NET 4.6 and Visual Studio 2015 together with discussion of the new Windows Runtime. Who this book is for This book is perfect for anyone who is interested in the new .NET Framework 4.6 and the C# language. Whether you are moving to .NET for the first time or are already writing applications using previous .NET versions, this book will provide you with a comprehensive grounding in the new technology and serve as a complete reference throughout your coding career. Table of Contents Part I: Introducing C# and the .NET Platform Chapter 1: The Philosophy of .NET Chapter 2: Building C# Applications Part II: Core C# Programming Chapter 3: Core C# Programming Constructs, Part I Chapter 4: Core C# Programming Constructs, Part II Part III: Object-Oriented Programming with C# Chapter 5: Understanding Encapsulation Chapter 6: Understanding Inheritance and Polymorphism Chapter 7: Understanding Structured Exception Handling Chapter 8: Working with Interfaces Part IV: Advanced C# Programming Chapter 9: Collections and Generics Chapter 10: Delegates, Events, and Lambda Expressions Chapter 11: Advanced C# Language Features Chapter 12: LINQ to Objects Chapter 13: Understanding Object Lifetime Part V: Programming with .NET Assemblies Chapter 14: Building and Configuring Class Libraries Chapter 15: Type Reflection, Late Binding, and Attribute-Based Programming Chapter 16: Dynamic Types and the Dynamic Language Runtime Chapter 17: Processes, AppDomains, and Object Contexts Chapter 18: Understanding CIL and the Role of Dynamic Assemblies Part VI: Introducing the .NET Base Class Libraries Chapter 19: Multithreaded, Parallel, and Async Programming Chapter 20: File I/O and Object Serialization Chapter 21: ADO.NET Part I: The Connected Layer Chapter 22: ADO.NET Part II: The Disconnected Layer Chapter 23: ADO.NET Part III: Entity Framework Chapter 24: Introducing LINQ to XML Chapter 25: Introducing Windows Communication Foundation Part VII: Windows Presentation Foundation Chapter 26: Introducing Windows Presentation Foundation and XAML Chapter 27: Programming with WPF Controls Chapter 28: WPF Graphics Rendering Services Chapter 29: WPF Resources, Animations, Styles, and Templates Chapter 30: Notifications, Commands, Validation, and MVVM Part VIII: ASP.NET Chapter 31: Introducing ASP.NET Web Forms Chapter 32: ASP.NET Web Controls, Master Pages, and Themes Chapter 33: ASP.NET State Management Techniques Chapter 34: ASP.NET MVC and Web API
Beginning: Microsoft Visual C# 2008 0 About the Authors 9 Credits 10 Contents 12 Introduction 30 Who This Book Is For 30 How This Book Is Structured 31 What You Need to Use This Book 34 Conventions 34 Source Code 35 Errata 35 p2p.wrox.com 36 Part I: The C# Language 38 Chapter 1: Introducing C# 40 What Is the .NET Framework? 40 What Is C#? 45 Visual Studio 2008 46 Summary 48 Chapter 2: Writing a C# Program 50 The Development Environments 51 Console Applications 55 Windows Forms Applications 61 Summary 66 Chapter 3: Variables and Expressions 68 Basic C# Syntax 69 Basic C# Console Application Structure 71 Variables 73 Expressions 83 Summary 93 Exercises 94 Chapter 4: Flow Control 96 Boolean Logic 96 The goto Statement 106 Branching 107 Looping 115 Summary 127 Exercises 127 Chapter 5: More About Variables 130 Type Conversion 130 Complex Variable Types 140 String Manipulation 155 Summary 160 Exercises 161 Chapter 6: Functions 162 Defining and Using Functions 163 Variable Scope 175 The Main() Function 181 Struct Functions 184 Overloading Functions 185 Delegates 187 Summary 190 Exercises 191 Chapter 7: Debugging and Error Handling 192 Debugging in VS and VCE 193 Error Handling 213 Summary 221 Exercises 221 Chapter 8: Introduction to Object-Oriented Programming 222 What Is Object-Oriented Programming? 223 OOP Techniques 229 OOP in Windows Applications 240 Summary 243 Exercises 243 Chapter 9: Defining Classes 246 Class Definitions in C# 246 System.Object 253 Constructors and Destructors 255 OOP Tools in VS and VCE 260 Class Library Projects 266 Interfaces Versus Abstract Classes 270 Struct Types 272 Summary 275 Exercises 276 Chapter 10: Defining Class Members 278 Member Definitions 278 Additional Class Member Topics 291 Interface Implementation 294 Partial Class Definitions 299 Partial Method Definitions 301 Example Application 302 Summary 313 Exercises 313 Chapter 11: Collections, Comparisons, and Conversions 314 Collections 314 Comparisons 340 Conversions 363 Summary 365 Exercises 366 Chapter 12: Generics 368 What Is a Generic? 368 Using Generics 370 Defining Generics 388 Summary 405 Exercises 405 Chapter 13: Additional OOP Techniques 408 The :: Operator and the Global Namespace Qualifier 408 Custom Exceptions 410 Events 412 Expanding and Using CardLib 426 Summary 434 Exercises 435 Chapter 14: C# 3.0 Language Enhancements 436 Initializers 437 Type Inference 443 Anonymous Types 445 Extension Methods 449 Lambda Expressions 455 Summary 466 Exercises 467 Part II: Windows Programming 468 Chapter 15: Basic Windows Programming 470 Controls 471 The Button Control 477 The Label and LinkLabel Controls 480 The TextBox Control 481 The RadioButton and CheckBox Controls 491 The RichTextBox Control 498 The ListBox and CheckedListBox Controls 506 The ListView Control 512 The TabControl Control 523 Summary 528 Exercises 529 Chapter 16: Advanced Windows Forms Features 530 Menus and Toolbars 531 Toolbars 538 SDI and MDI Applications 549 Creating Controls 561 Summary 572 Exercises 572 Chapter 17: Using Common Dialogs 574 Common Dialogs 574 How to Use Dialogs 576 File Dialogs 577 Printing 596 Print Preview 612 FontDialog and ColorDialog 614 Summary 618 Exercises 619 Chapter 18: Deploying Windows Applications 620 Deployment Overview 620 ClickOnce Deployment 621 Visual Studio Setup and Deployment Project Types 634 Microsoft Windows Installer Architecture 635 Creating an Installation Package for the SimpleEditor 639 Building the Project 654 Installation 654 Summary 659 Exercises 660 Part III: Web Programming 662 Chapter 19: Basic Web Programming 664 Overview 665 ASP.NET Runtime 665 Creating a Simple Page 666 Server Controls 673 Event Handlers 674 Input Validation 679 State Management 683 Authentication and Authorization 689 Reading and Writing to an SQL Server Database 697 Summary 706 Exercises 707 Chapter 20: Advanced Web Programming 708 Master Pages 708 Site Navigation 716 User Controls 717 Profiles 720 Web Parts 725 JavaScript 738 Summary 744 Exercises 745 Chapter 21: Web Services 746 Before Web Services 747 Where to Use Web Services 748 Web Services Architecture 751 Web Services and the .NET Framework 754 Creating a Simple ASP.NET Web Service 757 Testing the Web Service 759 Implementing a Windows Client 761 Calling the Service Asynchronously 765 Implementing an ASP.NET Client 768 Passing Data 769 Summary 773 Exercises 774 Chapter 22: Ajax Programming 776 Ajax Overview 776 Update Panel 778 Timer Control 783 Update Progress 784 Web Services 786 Extender Controls 792 Summary 794 Exercises 794 Chapter 23: Deploying Web Applications 796 Internet Information Services 796 IIS Configuration 797 Copying a Web Site 800 Publishing a Web Site 802 Windows Installer 804 Summary 809 Exercises 810 Part IV: Data Access 812 Chapter 24: File System Data 814 Streams 815 The Classes for Input and Output 815 Serialized Objects 842 Monitoring the File Structure 847 Summary 855 Exercises 855 Chapter 25: XML 856 XML Documents 856 Using XML in Your Application 865 Summary 884 Exercises 885 Chapter 26: Introduction to LINQ 886 LINQ Varieties 887 First LINQ Query 887 Using the LINQ Method Syntax and Lambda Expressions 892 Ordering Query Results 895 orderby Clause 897 Ordering Using Method Syntax 897 Querying a Large Data Set 899 Aggregate Operators 902 Querying Complex Objects 905 Projection: Creating New Objects in Queries 909 Projection: Method Syntax 912 Select Distinct Query 912 Any and All 914 Ordering By Multiple Levels 916 Multi-Level Ordering Method Syntax: ThenBy 918 Group Queries 918 Take and Skip 920 First and FirstOrDefault 923 Set Operators 924 Joins 928 Resources and Further Reading 929 Summary 930 Exercises 930 Chapter 27: LINQ to SQL 932 Object -Relational Mapping (ORM) 933 Installing SQL Server and the Northwind Sample Data 933 First LINQ to SQL Query 935 Navigating LINQ to SQL Relationships 944 Drilling Down Further with LINQ to SQL 948 Grouping, Ordering, and Other Advanced Queries in LINQ to SQL 951 Displaying Generated SQL 954 Data Binding with LINQ to SQL 958 Updating Bound Data with LINQ to SQL 965 Summary 966 Exercises 967 Chapter 28: ADO.NET and LINQ over DataSet 970 What Is ADO.NET? 971 Overview of ADO.NET Classes and Objects 974 Reading Data with the DataReader 977 Reading Data with the DataSet 985 Updating the Database 989 Accessing Multiple Tables in a DataSet 1002 XML and ADO.NET 1010 SQL Support in ADO.NET 1014 Using LINQ over DataSet with ADO.NET 1022 Summary 1027 Exercises 1027 Chapter 29: LINQ to XML 1030 LINQ to XML Functional Constructors 1031 Saving and Loading an XML Document 1035 Working with XML Fragments 1039 Generating XML from LINQ to SQL 1041 How to Query an XML Document 1046 Summary 1053 Exercises 1053 Part V: Additional Techniques 1054 Chapter 30: Attributes 1056 What Is an Attribute? 1056 Reflection 1060 Built-in Attributes 1063 Custom Attributes 1075 Summary 1083 Chapter 31: XML Documentation 1086 Adding XML Documentation 1087 Making Use of XML Documentation 1105 Summary 1110 Exercises 1110 Chapter 32: Networking 1112 Networking Overview 1112 Networking Programming Options 1120 WebClient 1121 WebRequest and WebResponse 1123 TcpListener and TcpClient 1133 Summary 1141 Exercises 1142 Chapter 33: Introduction to GDI+ 1144 Overview of Graphical Drawing 1145 Drawing Lines Using the Pen Class 1156 Drawing Shapes Using the Brush Class 1159 Drawing Text Using the Font Class 1161 Drawing Using Images 1165 Advanced Capabilities of GDI+ 1175 Summary 1177 Exercises 1178 Chapter 34: Windows Presentation Foundation 1180 What Is WPF? 1181 Anatomy of a Basic WPF Application 1185 WPF Fundamentals 1197 Programming with WPF 1237 Summary 1249 Exercises 1250 Chapter 35: Windows Communication Foundation 1252 What Is WCF ? 1253 WCF Concepts 1254 WCF Programming 1258 Summary 1282 Exercises 1283 Chapter 36: Windows Workflow Foundation 1284 Activities 1288 The Workflow Runtime 1303 Data Binding 1310 Summary 1315 Index 1316

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值