没有合适的资源?快使用搜索试试~ 我知道了~
CLR.via.C#.3rd.Edition.(2010) 第二部分 免费 英文版,超清晰
5星 · 超过95%的资源 需积分: 12 35 下载量 181 浏览量
2010-03-13
20:16:56
上传
评论
收藏 18.26MB PDF 举报
温馨提示
试读
446页
英文版,如其一介绍 CLR.via.C#.3rd.Edition.(2010) 第二部分 免费 英文版,超清晰
资源推荐
资源详情
资源评论
434 Part III Essential Types
if (d.GetType() == typeof(OneString)) {
// Just copy the String argument
Array.Copy(args, 2, callbackArgs, 0, callbackArgs.Length);
}
try {
// Invoke the delegate and show the result
Object result = d.DynamicInvoke(callbackArgs);
Console.WriteLine("Result = " + result);
}
catch (TargetParameterCountException) {
Console.WriteLine("Incorrect number of parameters specified.");
}
}
// This callback method takes 2 Int32 arguments
private static Object Add(Int32 n1, Int32 n2) {
return n1 + n2;
}
// This callback method takes 2 Int32 arguments
private static Object Subtract(Int32 n1, Int32 n2) {
return n1 - n2;
}
// This callback method takes 1 String argument
private static Object NumChars(String s1) {
return s1.Length;
}
// This callback method takes 1 String argument
private static Object Reverse(String s1) {
Char[] chars = s1.ToCharArray();
Array.Reverse(chars);
return new String(chars);
}
}
435
Chapter 18
Custom Attributes
In this chapter:
Using Custom Attributes ..............................................435
Defining Your Own Attribute Class .....................................439
Attribute Constructor and Field/Property Data Types . . . . . . . . . . . . . . . . . . . . . 443
Detecting the Use of a Custom Attribute ................................444
Matching Two Attribute Instances Against Each Other ....................448
Detecting the Use of a Custom Attribute Without Creating
Attribute-Derived Objects ...........................................451
Conditional Attribute Classes ..........................................454
In this chapter, I’ll discuss one of the most innovative features the Microsoft .NET Framework
has to offer: custom attributes. Custom attributes allow you to declaratively annotate your
code constructs, thereby enabling special features. Custom attributes allow information to be
defined and applied to almost any metadata table entry. This extensible metadata information
can be queried at runtime to dynamically alter the way code executes. As you use the various
.NET Framework technologies (Windows Forms, Web Forms, XML Web services, and so on),
you’ll see that they all take advantage of custom attributes, allowing developers to express
their intentions within code very easily. A solid understanding of custom attributes is neces-
sary for any .NET Framework developer.
Using Custom Attributes
Attributes, such as public, private, static, and so on, can be applied to types and
members. I think we’d all agree on the usefulness of applying attributes, but wouldn’t it be
even more useful if we could define our own attributes? For example, what if I could define a
type and somehow indicate that the type can be remoted via serialization? Or maybe I could
apply an attribute to a method to indicate that certain security permissions must be granted
before the method can execute.
Of course, creating and applying user-defined attributes to types and methods would be
great and convenient, but it would require the compiler to be aware of these attributes so it
would emit the attribute information into the resulting metadata. Because compiler vendors
usually prefer not to release the source code for their compiler, Microsoft came up with
another way to allow user-defined attributes. This mechanism, called custom attributes, is an
436 Part III Essential Types
incredibly powerful mechanism that’s useful at both application design time and runtime.
Anyone can define and use custom attributes, and all compilers that target the common
language runtime (CLR) must be designed to recognize custom attributes and emit them into
the resulting metadata.
The first thing you should realize about custom attributes is that they’re just a way to
associate additional information with a target. The compiler emits this additional information
into the managed module’s metadata. Most attributes have no meaning for the compiler;
the compiler simply detects the attributes in the source code and emits the corresponding
metadata.
The .NET Framework Class Library (FCL) defines literally hundreds of custom attributes that
can be applied to items in your own source code. Here are some examples:
n
Applying the DllImport attribute to a method informs the CLR that the implementa-
tion of the method is actually in unmanaged code contained in the specified DLL.
n
Applying the Serializable attribute to a type informs the serialization formatters that
an instance’s fields may be serialized and deserialized.
n
Applying the AssemblyVersion attribute to an assembly sets the version number of
the assembly.
n
Applying the Flags attribute to an enumerated type causes the enumerated type to
act as a set of bit flags.
Following is some C# code with many attributes applied to it. In C#, you apply a custom at-
tribute to a target by placing the attribute in square brackets immediately before the target.
It’s not important to understand what this code does. I just want you to see what attributes
look like.
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal sealed class OSVERSIONINFO {
public OSVERSIONINFO() {
OSVersionInfoSize = (UInt32) Marshal.SizeOf(this);
}
public UInt32 OSVersionInfoSize = 0;
public UInt32 MajorVersion = 0;
public UInt32 MinorVersion = 0;
public UInt32 BuildNumber = 0;
public UInt32 PlatformId = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public String CSDVersion = null;
}
Chapter 18 Custom Attributes 437
internal sealed class MyClass {
[DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
public static extern Boolean GetVersionEx([In, Out] OSVERSIONINFO ver);
}
In this case, the StructLayout attribute is applied to the OSVERSIONINFO class, the
MarshalAs attribute is applied to the CSDVersion field, the DllImport attribute is applied
to the GetVersionEx method, and the In and Out attributes are applied to GetVersionEx’s
ver parameter. Every programming language defines the syntax a developer must use in or-
der to apply a custom attribute to a target. Microsoft Visual Basic .NET, for example, requires
angle brackets (<, >) instead of square brackets.
The CLR allows attributes to be applied to just about anything that can be represented in a
file’s metadata. Most commonly, attributes are applied to entries in the following definition
tables: TypeDef (classes, structures, enumerations, interfaces, and delegates), MethodDef
(including constructors), ParamDef, FieldDef, PropertyDef, EventDef, AssemblyDef, and
ModuleDef. Specifically, C# allows you to apply an attribute only to source code that defines
any of the following targets: assembly, module, type (class, struct, enum, interface, delegate),
field, method (including constructors), method parameter, method return value, property,
event, and generic type parameter.
When you’re applying an attribute, C# allows you to specify a prefix specifically indicating
the target the attribute applies to. The following code shows all of the possible prefixes. In
many cases, if you leave out the prefix, the compiler can still determine the target an attri-
bute applies to, as shown in the previous example. In some cases, the prefix must be speci-
fied to make your intentions clear to the compiler. The prefixes shown in italics below are
mandatory.
using System;
[assembly: SomeAttr] // Applied to assembly
[module: SomeAttr] // Applied to module
[type: SomeAttr] // Applied to type
internal sealed class SomeType<[typevar: SomeAttr] T> { // Applied to generic type variable
[field: SomeAttr] // Applied to field
public Int32 SomeField = 0;
[return: SomeAttr] // Applied to return value
[method: SomeAttr] // Applied to method
public Int32 SomeMethod(
[param: SomeAttr] // Applied to parameter
Int32 SomeParam) { return SomeParam; }
[property: SomeAttr] // Applied to property
public String SomeProp {
[method: SomeAttr] // Applied to get accessor method
get { return null; }
剩余445页未读,继续阅读
资源评论
- prettyboy42013-05-09C# 底层,讲得很到位.很值得学习的C#提高书籍
youhaooo
- 粉丝: 52
- 资源: 29
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功