Programming Concepts
9849 단어 programming
Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection. For more information, see Reflection (C# and Visual Basic) .
Attributes have the following properties:
Using Attributes
Attributes can be placed on most any declaration, though a specific attribute might restrict the types of declarations on which it is valid. In C#, you specify an attribute by placing the name of the attribute, enclosed in square brackets ([]), above the declaration of the entity to which it applies. In Visual Basic, an attribute is enclosed in angle brackets (< >). It must appear immediately before the element to which it is applied, on the same line.
In this example, the SerializableAttribute attribute is used to apply a specific characteristic to a class:
using System;
[Serializable]
class SampleClass
{
// Objects of this type can be serialized.
}
A method with the attribute DllImportAttribute is declared like this:
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
extern static void SampleMethod();
More than one attribute can be placed on a declaration:
public sealed class InAttribute : Attribute
public sealed class OutAttribute : Attribute
using System.Runtime.InteropServices;
void MethodA([In][Out] ref double x) { }
void MethodB([Out][In] ref double x) { }
void MethodC([In, Out] ref double x) { }
Some attributes can be specified more than once for a given entity. An example of such a multiuse attribute is ConditionalAttribute:
using System.Diagnostics;
[Conditional("DEBUG"), Conditional("TEST1")]
void TraceMethod() { }
By convention, all attribute names end with the word "Attribute"to distinguish them from other items in the .NET Framework.
However, you do not need to specify the attribute suffix when using attributes in code.
For example, [DllImport] is equivalent to [DllImportAttribute], but DllImportAttribute is the attribute's actual name in the .NET Framework.
Reflection
Reflection provides objects (of type Type ) that describe assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them. For more information, see Extending Metadata Using Attributes .
Here's a simple example of reflection using the static method GetType - inherited by all types from the Object base class - to obtain the type of a variable:
// Using GetType to obtain type information:
using System;
int i = 0;
Type type = i.GetType();
Console.WriteLine(type);
출력 결과: System.Int32
The following example uses reflection to obtain the full name of the loaded assembly.
using System;
using System.Reflection;
Type type = typeof(int);
Assembly assembly = type.Assembly;
Console.WriteLine(assembly);
int i = 0;
type = i.GetType();
assembly = type.Assembly;
Console.WriteLine(assembly);
결과 출력:
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
The C# keywords protected and internal have no meaning in IL and are not used in the reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using reflection, use the IsAssembly property. To identify a protected internal method, use the IsFamilyOrAssembly .
Reflection Overview
Reflection is useful in the following situations:When you have to access attributes in your program's metadata. For more information, see Retrieving Information Stored in Attributes .For examining and instantiating types in an assembly.For building new types at runtime. Use classes in System.Reflection.Emit .For performing late binding, accessing methods on types created at run time. See the topic Dynamically Loading and Using Types .
Related Sections Reflection in the .NET Framework Viewing Type Information Reflection and Generic Types System.Reflection.Emit Retrieving Information Stored in Attributes
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
표준 Pascal 범위 내에서 Delphi 입문표준 Pascal (Standard Pascal) 에서 해설되고 있는 범위에서의 Delphi 는 어떻게 되어 있는지를, 문득 알고 싶어졌습니다. 이 기사는 ** "Delphi 콘솔 응용 프로그램에서 uses 절을 작...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.