PropertyBuilder 클래스
형식에 대한 속성을 정의합니다.
네임스페이스: System.Reflection.Emit
어셈블리: mscorlib(mscorlib.dll)
구문
‘선언
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
<ComVisibleAttribute(True)> _
Public NotInheritable Class PropertyBuilder
Inherits PropertyInfo
Implements _PropertyBuilder
‘사용 방법
Dim instance As PropertyBuilder
[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
public sealed class PropertyBuilder : PropertyInfo, _PropertyBuilder
[ClassInterfaceAttribute(ClassInterfaceType::None)]
[ComVisibleAttribute(true)]
public ref class PropertyBuilder sealed : public PropertyInfo, _PropertyBuilder
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.None) */
/** @attribute ComVisibleAttribute(true) */
public final class PropertyBuilder extends PropertyInfo implements _PropertyBuilder
ClassInterfaceAttribute(ClassInterfaceType.None)
ComVisibleAttribute(true)
public final class PropertyBuilder extends PropertyInfo implements _PropertyBuilder
설명
참고
이 클래스에 적용되는 HostProtectionAttribute 특성의 Resources 속성 값은 MayLeakOnAbort입니다. HostProtectionAttribute는 대개 아이콘을 두 번 클릭하거나, 명령을 입력하거나, 브라우저에서 URL을 입력하여 시작되는 데스크톱 응용 프로그램에 영향을 미치지 않습니다. 자세한 내용은 HostProtectionAttribute 클래스나 SQL Server 프로그래밍 및 호스트 보호 특성을 참조하십시오.
PropertyBuilder는 항상 TypeBuilder에 연결됩니다. TypeBuilder.DefineProperty 메서드는 클라이언트에 새 PropertyBuilder를 반환합니다.
예제
다음 코드 예제에서는 TypeBuilder.DefineProperty를 통해 얻은 PropertyBuilder를 사용하여, 속성 프레임워크 및 관련된 MethodBuilder를 만들어 속성에 IL 논리를 구현함으로써 동적 형식의 속성을 구현하는 방법을 보여 줍니다.
Imports System
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
Class PropertyBuilderDemo
Public Shared Function BuildDynamicTypeWithProperties() As Type
Dim myDomain As AppDomain = Thread.GetDomain()
Dim myAsmName As New AssemblyName()
myAsmName.Name = "MyDynamicAssembly"
' To generate a persistable assembly, specify AssemblyBuilderAccess.RunAndSave.
Dim myAsmBuilder As AssemblyBuilder = myDomain.DefineDynamicAssembly(myAsmName, _
AssemblyBuilderAccess.RunAndSave)
' Generate a persistable, single-module assembly.
Dim myModBuilder As ModuleBuilder = _
myAsmBuilder.DefineDynamicModule(myAsmName.Name, myAsmName.Name & ".dll")
Dim myTypeBuilder As TypeBuilder = myModBuilder.DefineType("CustomerData", TypeAttributes.Public)
' Define a private field to hold the property value.
Dim customerNameBldr As FieldBuilder = myTypeBuilder.DefineField("customerName", _
GetType(String), FieldAttributes.Private)
' The last argument of DefineProperty is Nothing, because the
' property has no parameters. (If you don't specify Nothing, you must
' specify an array of Type objects. For a parameterless property,
' use an array with no elements: New Type() {})
Dim custNamePropBldr As PropertyBuilder = _
myTypeBuilder.DefineProperty("CustomerName", _
PropertyAttributes.HasDefault, _
GetType(String), _
Nothing)
' The property set and property get methods require a special
' set of attributes.
Dim getSetAttr As MethodAttributes = _
MethodAttributes.Public Or MethodAttributes.SpecialName _
Or MethodAttributes.HideBySig
' Define the "get" accessor method for CustomerName.
Dim custNameGetPropMthdBldr As MethodBuilder = _
myTypeBuilder.DefineMethod("GetCustomerName", _
getSetAttr, _
GetType(String), _
Type.EmptyTypes)
Dim custNameGetIL As ILGenerator = custNameGetPropMthdBldr.GetILGenerator()
custNameGetIL.Emit(OpCodes.Ldarg_0)
custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr)
custNameGetIL.Emit(OpCodes.Ret)
' Define the "set" accessor method for CustomerName.
Dim custNameSetPropMthdBldr As MethodBuilder = _
myTypeBuilder.DefineMethod("get_CustomerName", _
getSetAttr, _
Nothing, _
New Type() {GetType(String)})
Dim custNameSetIL As ILGenerator = custNameSetPropMthdBldr.GetILGenerator()
custNameSetIL.Emit(OpCodes.Ldarg_0)
custNameSetIL.Emit(OpCodes.Ldarg_1)
custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr)
custNameSetIL.Emit(OpCodes.Ret)
' Last, we must map the two methods created above to our PropertyBuilder to
' their corresponding behaviors, "get" and "set" respectively.
custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr)
custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr)
Dim retval As Type = myTypeBuilder.CreateType()
' Save the assembly so it can be examined with Ildasm.exe,
' or referenced by a test program.
myAsmBuilder.Save(myAsmName.Name & ".dll")
return retval
End Function 'BuildDynamicTypeWithProperties
Public Shared Sub Main()
Dim custDataType As Type = BuildDynamicTypeWithProperties()
Dim custDataPropInfo As PropertyInfo() = custDataType.GetProperties()
Dim pInfo As PropertyInfo
For Each pInfo In custDataPropInfo
Console.WriteLine("Property '{0}' created!", pInfo.ToString())
Next pInfo
Console.WriteLine("---")
' Note that when invoking a property, you need to use the proper BindingFlags -
' BindingFlags.SetProperty when you invoke the "set" behavior, and
' BindingFlags.GetProperty when you invoke the "get" behavior. Also note that
' we invoke them based on the name we gave the property, as expected, and not
' the name of the methods we bound to the specific property behaviors.
Dim custData As Object = Activator.CreateInstance(custDataType)
custDataType.InvokeMember("CustomerName", BindingFlags.SetProperty, Nothing, _
custData, New Object() {"Joe User"})
Console.WriteLine("The customerName field of instance custData has been set to '{0}'.", _
custDataType.InvokeMember("CustomerName", BindingFlags.GetProperty, _
Nothing, custData, New Object() {}))
End Sub 'Main
End Class 'PropertyBuilderDemo
' --- O U T P U T ---
' The output should be as follows:
' -------------------
' Property 'System.String CustomerName [System.String]' created!
' ---
' The customerName field of instance custData has been set to 'Joe User'.
' -------------------
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
class PropertyBuilderDemo
{
public static Type BuildDynamicTypeWithProperties()
{
AppDomain myDomain = Thread.GetDomain();
AssemblyName myAsmName = new AssemblyName();
myAsmName.Name = "MyDynamicAssembly";
// To generate a persistable assembly, specify AssemblyBuilderAccess.RunAndSave.
AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(myAsmName,
AssemblyBuilderAccess.RunAndSave);
// Generate a persistable single-module assembly.
ModuleBuilder myModBuilder =
myAsmBuilder.DefineDynamicModule(myAsmName.Name, myAsmName.Name + ".dll");
TypeBuilder myTypeBuilder = myModBuilder.DefineType("CustomerData",
TypeAttributes.Public);
FieldBuilder customerNameBldr = myTypeBuilder.DefineField("customerName",
typeof(string),
FieldAttributes.Private);
// The last argument of DefineProperty is null, because the
// property has no parameters. (If you don't specify null, you must
// specify an array of Type objects. For a parameterless property,
// use an array with no elements: new Type[] {})
PropertyBuilder custNamePropBldr = myTypeBuilder.DefineProperty("CustomerName",
PropertyAttributes.HasDefault,
typeof(string),
null);
// The property set and property get methods require a special
// set of attributes.
MethodAttributes getSetAttr =
MethodAttributes.Public | MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
// Define the "get" accessor method for CustomerName.
MethodBuilder custNameGetPropMthdBldr =
myTypeBuilder.DefineMethod("get_CustomerName",
getSetAttr,
typeof(string),
Type.EmptyTypes);
ILGenerator custNameGetIL = custNameGetPropMthdBldr.GetILGenerator();
custNameGetIL.Emit(OpCodes.Ldarg_0);
custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
custNameGetIL.Emit(OpCodes.Ret);
// Define the "set" accessor method for CustomerName.
MethodBuilder custNameSetPropMthdBldr =
myTypeBuilder.DefineMethod("set_CustomerName",
getSetAttr,
null,
new Type[] { typeof(string) });
ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();
custNameSetIL.Emit(OpCodes.Ldarg_0);
custNameSetIL.Emit(OpCodes.Ldarg_1);
custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
custNameSetIL.Emit(OpCodes.Ret);
// Last, we must map the two methods created above to our PropertyBuilder to
// their corresponding behaviors, "get" and "set" respectively.
custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);
Type retval = myTypeBuilder.CreateType();
// Save the assembly so it can be examined with Ildasm.exe,
// or referenced by a test program.
myAsmBuilder.Save(myAsmName.Name + ".dll");
return retval;
}
public static void Main()
{
Type custDataType = BuildDynamicTypeWithProperties();
PropertyInfo[] custDataPropInfo = custDataType.GetProperties();
foreach (PropertyInfo pInfo in custDataPropInfo) {
Console.WriteLine("Property '{0}' created!", pInfo.ToString());
}
Console.WriteLine("---");
// Note that when invoking a property, you need to use the proper BindingFlags -
// BindingFlags.SetProperty when you invoke the "set" behavior, and
// BindingFlags.GetProperty when you invoke the "get" behavior. Also note that
// we invoke them based on the name we gave the property, as expected, and not
// the name of the methods we bound to the specific property behaviors.
object custData = Activator.CreateInstance(custDataType);
custDataType.InvokeMember("CustomerName", BindingFlags.SetProperty,
null, custData, new object[]{ "Joe User" });
Console.WriteLine("The customerName field of instance custData has been set to '{0}'.",
custDataType.InvokeMember("CustomerName", BindingFlags.GetProperty,
null, custData, new object[]{ }));
}
}
// --- O U T P U T ---
// The output should be as follows:
// -------------------
// Property 'System.String CustomerName [System.String]' created!
// ---
// The customerName field of instance custData has been set to 'Joe User'.
// -------------------
using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
Type^ BuildDynamicTypeWithProperties()
{
AppDomain^ myDomain = Thread::GetDomain();
AssemblyName^ myAsmName = gcnew AssemblyName;
myAsmName->Name = "MyDynamicAssembly";
// To generate a persistable assembly, specify AssemblyBuilderAccess::RunAndSave.
AssemblyBuilder^ myAsmBuilder =
myDomain->DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess::RunAndSave );
// Generate a persistable single-module assembly.
ModuleBuilder^ myModBuilder =
myAsmBuilder->DefineDynamicModule( myAsmName->Name, myAsmName->Name + ".dll" );
TypeBuilder^ myTypeBuilder = myModBuilder->DefineType( "CustomerData", TypeAttributes::Public );
// Define a private field to hold the property value.
FieldBuilder^ customerNameBldr = myTypeBuilder->DefineField( "customerName", String::typeid, FieldAttributes::Private );
// The last argument of DefineProperty is an empty array of Type
// objects, because the property has no parameters. (Alternatively,
// you can specify a null value.)
PropertyBuilder^ custNamePropBldr =
myTypeBuilder->DefineProperty( "CustomerName", PropertyAttributes::HasDefault, String::typeid, gcnew array<Type^>(0) );
// The property set and property get methods require a special
// set of attributes.
MethodAttributes getSetAttr =
MethodAttributes::Public | MethodAttributes::SpecialName |
MethodAttributes::HideBySig;
// Define the "get" accessor method for CustomerName.
MethodBuilder^ custNameGetPropMthdBldr =
myTypeBuilder->DefineMethod( "get_CustomerName",
getSetAttr,
String::typeid,
Type::EmptyTypes );
ILGenerator^ custNameGetIL = custNameGetPropMthdBldr->GetILGenerator();
custNameGetIL->Emit( OpCodes::Ldarg_0 );
custNameGetIL->Emit( OpCodes::Ldfld, customerNameBldr );
custNameGetIL->Emit( OpCodes::Ret );
// Define the "set" accessor method for CustomerName.
array<Type^>^temp2 = {String::typeid};
MethodBuilder^ custNameSetPropMthdBldr =
myTypeBuilder->DefineMethod( "set_CustomerName",
getSetAttr,
nullptr,
temp2 );
ILGenerator^ custNameSetIL = custNameSetPropMthdBldr->GetILGenerator();
custNameSetIL->Emit( OpCodes::Ldarg_0 );
custNameSetIL->Emit( OpCodes::Ldarg_1 );
custNameSetIL->Emit( OpCodes::Stfld, customerNameBldr );
custNameSetIL->Emit( OpCodes::Ret );
// Last, we must map the two methods created above to our PropertyBuilder to
// their corresponding behaviors, "get" and "set" respectively.
custNamePropBldr->SetGetMethod( custNameGetPropMthdBldr );
custNamePropBldr->SetSetMethod( custNameSetPropMthdBldr );
Type^ retval = myTypeBuilder->CreateType();
// Save the assembly so it can be examined with Ildasm.exe,
// or referenced by a test program.
myAsmBuilder->Save(myAsmName->Name + ".dll");
return retval;
}
int main()
{
Type^ custDataType = BuildDynamicTypeWithProperties();
array<PropertyInfo^>^custDataPropInfo = custDataType->GetProperties();
System::Collections::IEnumerator^ myEnum = custDataPropInfo->GetEnumerator();
while ( myEnum->MoveNext() )
{
PropertyInfo^ pInfo = safe_cast<PropertyInfo^>(myEnum->Current);
Console::WriteLine( "Property '{0}' created!", pInfo );
}
Console::WriteLine( "---" );
// Note that when invoking a property, you need to use the proper BindingFlags -
// BindingFlags::SetProperty when you invoke the "set" behavior, and
// BindingFlags::GetProperty when you invoke the "get" behavior. Also note that
// we invoke them based on the name we gave the property, as expected, and not
// the name of the methods we bound to the specific property behaviors.
Object^ custData = Activator::CreateInstance( custDataType );
array<Object^>^temp3 = {"Joe User"};
custDataType->InvokeMember( "CustomerName", BindingFlags::SetProperty, nullptr, custData, temp3 );
Console::WriteLine( "The customerName field of instance custData has been set to '{0}'.", custDataType->InvokeMember( "CustomerName", BindingFlags::GetProperty, nullptr, custData, gcnew array<Object^>(0) ) );
}
// --- O U T P U T ---
// The output should be as follows:
// -------------------
// Property 'System.String CustomerName [System.String]' created!
// ---
// The customerName field of instance custData has been set to 'Joe User'.
// -------------------
상속 계층 구조
System.Object
System.Reflection.MemberInfo
System.Reflection.PropertyInfo
System.Reflection.Emit.PropertyBuilder
스레드로부터의 안전성
이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.
플랫폼
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.
버전 정보
.NET Framework
2.0, 1.1, 1.0에서 지원