Export (0) Print
Expand All

FieldBuilder Class

Defines and represents a field. This class cannot be inherited.

For a list of all members of this type, see FieldBuilder Members.

System.Object
   System.Reflection.MemberInfo
      System.Reflection.FieldInfo
         System.Reflection.Emit.FieldBuilder

[Visual Basic]
NotInheritable Public Class FieldBuilder
   Inherits FieldInfo
[C#]
public sealed class FieldBuilder : FieldInfo
[C++]
public __gc __sealed class FieldBuilder : public FieldInfo
[JScript]
public class FieldBuilder extends FieldInfo

Thread Safety

Reflection Emit is thread-safe when using assemblies that were created with the AppDomain.DefineDynamicAssembly method with the Boolean parameter isSynchronized set to true.

Remarks

Get an instance of FieldBuilder by calling DefineField, DefineInitializedData, or DefineUninitializedData.

Note   The SetValue method is currently not supported. As a workaround, retrieve the FieldInfo by reflecting on the finished type and call SetValue to set the value of the field.

Example

[Visual Basic, C#, C++] The following code sample illustrates the use of FieldBuilder.

[Visual Basic] 
Imports System
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit

Public Class FieldBuilder_Sample
   Private Shared Function CreateType(currentDomain As AppDomain) As Type

      ' Create an assembly.
      Dim myAssemblyName As New AssemblyName()
      myAssemblyName.Name = "DynamicAssembly"
      Dim myAssembly As AssemblyBuilder = currentDomain.DefineDynamicAssembly(myAssemblyName, _
                                                AssemblyBuilderAccess.Run)
      ' Create a dynamic module in Dynamic Assembly.
      Dim myModuleBuilder As ModuleBuilder = myAssembly.DefineDynamicModule("MyModule")
      ' Define a public class named "MyClass" in the assembly.
      Dim myTypeBuilder As TypeBuilder = myModuleBuilder.DefineType("MyClass", _
                                          TypeAttributes.Public)
      ' Define a private String field named "MyField" in the type.
      Dim myFieldBuilder As FieldBuilder = myTypeBuilder.DefineField("MyField", _
                  GetType(String), FieldAttributes.Private Or FieldAttributes.Static)
      ' Create the constructor.
      Dim constructorArgs As Type() = {GetType(String)}
      Dim constructor As ConstructorBuilder = _
                  myTypeBuilder.DefineConstructor(MethodAttributes.Public, _
                           CallingConventions.Standard, constructorArgs)
      Dim constructorIL As ILGenerator = constructor.GetILGenerator()
      constructorIL.Emit(OpCodes.Ldarg_0)
      Dim superConstructor As ConstructorInfo = GetType(Object).GetConstructor(New Type() {})
      constructorIL.Emit(OpCodes.Call, superConstructor)
      constructorIL.Emit(OpCodes.Ldarg_0)
      constructorIL.Emit(OpCodes.Ldarg_1)
      constructorIL.Emit(OpCodes.Stfld, myFieldBuilder)
      constructorIL.Emit(OpCodes.Ret)

      ' Create the MyMethod method.
      Dim myMethodBuilder As MethodBuilder = myTypeBuilder.DefineMethod("MyMethod",  _
                        MethodAttributes.Public, GetType(String), Nothing)
      Dim methodIL As ILGenerator = myMethodBuilder.GetILGenerator()
      methodIL.Emit(OpCodes.Ldarg_0)
      methodIL.Emit(OpCodes.Ldfld, myFieldBuilder)
      methodIL.Emit(OpCodes.Ret)
      Console.WriteLine("Name               :" + myFieldBuilder.Name)
      Console.WriteLine("DeclaringType      : " + myFieldBuilder.DeclaringType.ToString())
      Console.WriteLine("Type               :" + myFieldBuilder.FieldType.ToString())
      Console.WriteLine("Token              :" + myFieldBuilder.GetToken().Token.ToString())
      Return myTypeBuilder.CreateType()
   End Function 'CreateType
   Public Shared Sub Main()
      Try
         Dim myType As Type = CreateType(Thread.GetDomain())
         ' Create an instance of the "HelloWorld" class.
         Dim helloWorld As Object = Activator.CreateInstance(myType, New Object() {"HelloWorld"})
         ' Invoke the "MyMethod" method of the "MyClass" class.
         Dim myObject As Object = myType.InvokeMember("MyMethod", _
                     BindingFlags.InvokeMethod, Nothing, helloWorld, Nothing)
         Console.WriteLine("MyClass.MyMethod returned: " & Microsoft.VisualBasic.Chr(34) & myObject  & Microsoft.VisualBasic.Chr(34) )
     Catch e as Exception
            Console.WriteLine("Exception Caught "+e.Message)
     End Try
   End Sub 'Main
End Class 'FieldBuilder_Sample

[C#] 
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;


public class FieldBuilder_Sample
{
   private static Type CreateType(AppDomain currentDomain)
   {

      // Create an assembly.
      AssemblyName myAssemblyName = new AssemblyName();
      myAssemblyName.Name = "DynamicAssembly";
      AssemblyBuilder myAssembly =
                     currentDomain.DefineDynamicAssembly(myAssemblyName,AssemblyBuilderAccess.Run);
      // Create a dynamic module in Dynamic Assembly.
      ModuleBuilder myModuleBuilder=myAssembly.DefineDynamicModule("MyModule");
      // Define a public class named "MyClass" in the assembly.
      TypeBuilder myTypeBuilder= myModuleBuilder.DefineType("MyClass",TypeAttributes.Public);

      // Define a private String field named "MyField" in the type.
      FieldBuilder myFieldBuilder= myTypeBuilder.DefineField("MyField",
          typeof(string),FieldAttributes.Private|FieldAttributes.Static);
      // Create the constructor.
      Type[] constructorArgs = { typeof(String) };
      ConstructorBuilder constructor = myTypeBuilder.DefineConstructor(
         MethodAttributes.Public, CallingConventions.Standard, constructorArgs);
      ILGenerator constructorIL = constructor.GetILGenerator();
      constructorIL.Emit(OpCodes.Ldarg_0);
      ConstructorInfo superConstructor = typeof(Object).GetConstructor(new Type[0]);
      constructorIL.Emit(OpCodes.Call, superConstructor);
      constructorIL.Emit(OpCodes.Ldarg_0);
      constructorIL.Emit(OpCodes.Ldarg_1);
      constructorIL.Emit(OpCodes.Stfld, myFieldBuilder);
      constructorIL.Emit(OpCodes.Ret);

      // Create the MyMethod method.
      MethodBuilder myMethodBuilder= myTypeBuilder.DefineMethod("MyMethod",
                           MethodAttributes.Public,typeof(String),null);
      ILGenerator methodIL = myMethodBuilder.GetILGenerator();
      methodIL.Emit(OpCodes.Ldarg_0);
      methodIL.Emit(OpCodes.Ldfld, myFieldBuilder);
      methodIL.Emit(OpCodes.Ret);
      Console.WriteLine("Name               :"+myFieldBuilder.Name);
      Console.WriteLine("DeclaringType      : "+myFieldBuilder.DeclaringType);
      Console.WriteLine("Type               :"+myFieldBuilder.FieldType);
      Console.WriteLine("Token              :"+myFieldBuilder.GetToken().Token);
      return myTypeBuilder.CreateType();
   }


   public static void Main()
   {
      try
      {
         Type myType = CreateType(Thread.GetDomain());
         // Create an instance of the "HelloWorld" class.
         Object helloWorld = Activator.CreateInstance(myType, new Object[] { "HelloWorld" });
         // Invoke the "MyMethod" method of the "MyClass" class.
         Object myObject  = myType.InvokeMember("MyMethod",
                        BindingFlags.InvokeMethod, null, helloWorld, null);
         Console.WriteLine("MyClass.MyMethod returned: \"" + myObject + "\"");
      }
      catch( Exception e)
      {
         Console.WriteLine("Exception Caught "+e.Message);
      }
  }
}

[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;

Type* CreateType(AppDomain* currentDomain)
{

   // Create an assembly.
   AssemblyName* myAssemblyName = new AssemblyName();
   myAssemblyName->Name = S"DynamicAssembly";
   AssemblyBuilder* myAssembly =
      currentDomain->DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess::Run);
   // Create a dynamic module in Dynamic Assembly.
   ModuleBuilder* myModuleBuilder=myAssembly->DefineDynamicModule(S"MyModule");
   // Define a public class named S"MyClass" in the assembly.
   TypeBuilder* myTypeBuilder= myModuleBuilder->DefineType(S"MyClass", TypeAttributes::Public);

   // Define a private String field named S"MyField" in the type.
   FieldBuilder* myFieldBuilder= myTypeBuilder->DefineField(S"MyField",
      __typeof(String), static_cast<FieldAttributes>(FieldAttributes::Private|FieldAttributes::Static));
   // Create the constructor.
   Type* constructorArgs[] = { __typeof(String) };
   ConstructorBuilder* constructor = myTypeBuilder->DefineConstructor(MethodAttributes::Public, CallingConventions::Standard, constructorArgs);
   ILGenerator* constructorIL = constructor->GetILGenerator();
   constructorIL->Emit(OpCodes::Ldarg_0);
   ConstructorInfo* superConstructor = __typeof(Object)->GetConstructor(new Type*[0]);
   constructorIL->Emit(OpCodes::Call, superConstructor);
   constructorIL->Emit(OpCodes::Ldarg_0);
   constructorIL->Emit(OpCodes::Ldarg_1);
   constructorIL->Emit(OpCodes::Stfld, myFieldBuilder);
   constructorIL->Emit(OpCodes::Ret);

   // Create the MyMethod method.
   MethodBuilder* myMethodBuilder= myTypeBuilder->DefineMethod(S"MyMethod",
      MethodAttributes::Public, __typeof(String), 0);
   ILGenerator* methodIL = myMethodBuilder->GetILGenerator();
   methodIL->Emit(OpCodes::Ldarg_0);
   methodIL->Emit(OpCodes::Ldfld, myFieldBuilder);
   methodIL->Emit(OpCodes::Ret);
   Console::WriteLine(S"Name               : {0}", myFieldBuilder->Name);
   Console::WriteLine(S"DeclaringType      : {0}", myFieldBuilder->DeclaringType);
   Console::WriteLine(S"Type               : {0}", myFieldBuilder->FieldType);
   Console::WriteLine(S"Token              : {0}", __box(myFieldBuilder->GetToken().Token));
   return myTypeBuilder->CreateType();
}


int main() {
   try {
      Type* myType = CreateType(Thread::GetDomain());
      // Create an instance of the S"HelloWorld" class.
      Object* type[] = { S"HelloWorld" };
      Object* helloWorld = Activator::CreateInstance(myType, type);
      // Invoke the S"MyMethod" method of the S"MyClass" class.
      Object* myObject  = myType->InvokeMember(S"MyMethod",
         BindingFlags::InvokeMethod, 0, helloWorld, 0);
      Console::WriteLine(S"MyClass::MyMethod returned: \"{0}\"", myObject);
   } catch (Exception* e) {
      Console::WriteLine(S"Exception Caught {0}", e->Message);
   }
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Reflection.Emit

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: Mscorlib (in Mscorlib.dll)

See Also

FieldBuilder Members | System.Reflection.Emit Namespace

Show:
© 2015 Microsoft