本文整理汇总了C#中TypeBuilder.DefineField方法的典型用法代码示例。如果您正苦于以下问题:C# TypeBuilder.DefineField方法的具体用法?C# TypeBuilder.DefineField怎么用?C# TypeBuilder.DefineField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TypeBuilder
的用法示例。
在下文中一共展示了TypeBuilder.DefineField方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateAutoImplementedProperty
public static void CreateAutoImplementedProperty(TypeBuilder builder, string propertyName, Type propertyType)
{
const string PrivateFieldPrefix = "m_";
const string GetterPrefix = "get_";
const string SetterPrefix = "set_";
// Generate the field.
FieldBuilder fieldBuilder = builder.DefineField(string.Concat(PrivateFieldPrefix, propertyName), propertyType, FieldAttributes.Private);
// Generate the property
PropertyBuilder propertyBuilder = builder.DefineProperty(propertyName, System.Reflection.PropertyAttributes.HasDefault, propertyType, null);
// Property getter and setter attributes.
MethodAttributes propertyMethodAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
// Define the getter method.
MethodBuilder getterMethod = builder.DefineMethod(string.Concat(GetterPrefix, propertyName), propertyMethodAttributes, propertyType, Type.EmptyTypes);
// Emit the IL code.
// ldarg.0
// ldfld,_field
// ret
ILGenerator getterILCode = getterMethod.GetILGenerator();
getterILCode.Emit(OpCodes.Ldarg_0);
getterILCode.Emit(OpCodes.Ldfld, fieldBuilder);
getterILCode.Emit(OpCodes.Ret);
// Define the setter method.
MethodBuilder setterMethod = builder.DefineMethod(string.Concat(SetterPrefix, propertyName), propertyMethodAttributes, null, new Type[] { propertyType });
// Emit the IL code.
// ldarg.0
// ldarg.1
// stfld,_field
// ret
ILGenerator setterILCode = setterMethod.GetILGenerator();
setterILCode.Emit(OpCodes.Ldarg_0);
setterILCode.Emit(OpCodes.Ldarg_1);
setterILCode.Emit(OpCodes.Stfld, fieldBuilder);
setterILCode.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getterMethod);
propertyBuilder.SetSetMethod(setterMethod);
}
示例2: CreateProperty
private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
{
FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
ILGenerator getIl = getPropMthdBldr.GetILGenerator();
getIl.Emit(OpCodes.Ldarg_0);
getIl.Emit(OpCodes.Ldfld, fieldBuilder);
getIl.Emit(OpCodes.Ret);
MethodBuilder setPropMthdBldr =
tb.DefineMethod("set_" + propertyName,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig,
null, new[] { propertyType });
ILGenerator setIl = setPropMthdBldr.GetILGenerator();
Label modifyProperty = setIl.DefineLabel();
Label exitSet = setIl.DefineLabel();
setIl.MarkLabel(modifyProperty);
setIl.Emit(OpCodes.Ldarg_0);
setIl.Emit(OpCodes.Ldarg_1);
setIl.Emit(OpCodes.Stfld, fieldBuilder);
setIl.Emit(OpCodes.Nop);
setIl.MarkLabel(exitSet);
setIl.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getPropMthdBldr);
propertyBuilder.SetSetMethod(setPropMthdBldr);
}
示例3: Define
public override bool Define ()
{
if (!base.Define ())
return false;
if (!BuiltinTypeSpec.IsPrimitiveType (MemberType)) {
Report.Error (1663, Location,
"`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
GetSignatureForError ());
} else if (declarators != null) {
var t = new TypeExpression (MemberType, TypeExpression.Location);
int index = Parent.PartialContainer.Fields.IndexOf (this);
foreach (var d in declarators) {
var f = new FixedField (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
f.initializer = d.Initializer;
((ConstInitializer) f.initializer).Name = d.Name.Value;
Parent.PartialContainer.Fields.Insert (++index, f);
}
}
// Create nested fixed buffer container
string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
Compiler.BuiltinTypes.ValueType.GetMetaInfo ());
var ffield = fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
var element_spec = new FieldSpec (null, this, MemberType, ffield, ModFlags);
spec = new FixedFieldSpec (Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
Parent.MemberCache.AddMember (spec);
return true;
}
示例4: WriteGetKeyImpl
private void WriteGetKeyImpl(TypeBuilder type, bool hasInheritance, SerializerPair[] methodPairs, Compiler.CompilerContext.ILVersion ilVersion, string assemblyName, out ILGenerator il, out int knownTypesCategory, out FieldBuilder knownTypes, out Type knownTypesLookupType)
{
il = Override(type, "GetKeyImpl");
Compiler.CompilerContext ctx = new Compiler.CompilerContext(il, false, false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(System.Type), true));
if (types.Count <= KnownTypes_ArrayCutoff)
{
knownTypesCategory = KnownTypes_Array;
knownTypesLookupType = MapType(typeof(System.Type[]), true);
}
else
{
#if NO_GENERICS
knownTypesLookupType = null;
#else
knownTypesLookupType = MapType(typeof(System.Collections.Generic.Dictionary<System.Type, int>), false);
#endif
if (knownTypesLookupType == null)
{
knownTypesLookupType = MapType(typeof(Hashtable), true);
knownTypesCategory = KnownTypes_Hashtable;
}
else
{
knownTypesCategory = KnownTypes_Dictionary;
}
}
knownTypes = type.DefineField("knownTypes", knownTypesLookupType, FieldAttributes.Private | FieldAttributes.InitOnly | FieldAttributes.Static);
switch (knownTypesCategory)
{
case KnownTypes_Array:
{
il.Emit(OpCodes.Ldsfld, knownTypes);
il.Emit(OpCodes.Ldarg_1);
// note that Array.IndexOf is not supported under CF
il.EmitCall(OpCodes.Callvirt, MapType(typeof(IList)).GetMethod(
"IndexOf", new Type[] { MapType(typeof(object)) }), null);
if (hasInheritance)
{
il.DeclareLocal(MapType(typeof(int))); // loc-0
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Stloc_0);
BasicList getKeyLabels = new BasicList();
int lastKey = -1;
for (int i = 0; i < methodPairs.Length; i++)
{
if (methodPairs[i].MetaKey == methodPairs[i].BaseKey) break;
if (lastKey == methodPairs[i].BaseKey)
{ // add the last label again
getKeyLabels.Add(getKeyLabels[getKeyLabels.Count - 1]);
}
else
{ // add a new unique label
getKeyLabels.Add(ctx.DefineLabel());
lastKey = methodPairs[i].BaseKey;
}
}
Compiler.CodeLabel[] subtypeLabels = new Compiler.CodeLabel[getKeyLabels.Count];
getKeyLabels.CopyTo(subtypeLabels, 0);
ctx.Switch(subtypeLabels);
il.Emit(OpCodes.Ldloc_0); // not a sub-type; use the original value
il.Emit(OpCodes.Ret);
lastKey = -1;
// now output the different branches per sub-type (not derived type)
for (int i = subtypeLabels.Length - 1; i >= 0; i--)
{
if (lastKey != methodPairs[i].BaseKey)
{
lastKey = methodPairs[i].BaseKey;
// find the actual base-index for this base-key (i.e. the index of
// the base-type)
int keyIndex = -1;
for (int j = subtypeLabels.Length; j < methodPairs.Length; j++)
{
if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey)
{
keyIndex = j;
break;
}
}
ctx.MarkLabel(subtypeLabels[i]);
Compiler.CompilerContext.LoadValue(il, keyIndex);
il.Emit(OpCodes.Ret);
}
}
}
else
{
il.Emit(OpCodes.Ret);
}
}
break;
case KnownTypes_Dictionary:
{
LocalBuilder result = il.DeclareLocal(MapType(typeof(int)));
//.........这里部分代码省略.........
示例5: Emit
public void Emit(TypeBuilder Builder)
{
if (CLRType != null)
{
try
{
// see: http://msdn.microsoft.com/en-us/library/System.Reflection.Emit.PropertyBuilder.aspx for more info
Type StorageType = (Type != ReflectedType.ARRAY) ? CLRType.MakeArrayType() : CLRType;
Type PropertyType = (ArrayDim > 1) ? CLRType.MakeArrayType() : CLRType;
// Add the private field, named _<Name>
FieldBuilder Field = Builder.DefineField(FieldName, StorageType, FieldAttributes.Private);
// Now add a public property to wrap the field, <Name>
PropertyBuilder Prop = Builder.DefineProperty(Name, System.Reflection.PropertyAttributes.HasDefault, PropertyType, null);
// Put the property in a category
ConstructorInfo CategoryCtor = typeof(CategoryAttribute).GetConstructor(new System.Type[] { typeof(string) });
CustomAttributeBuilder CategoryAttr = new CustomAttributeBuilder(CategoryCtor, new object[] {Category});
Prop.SetCustomAttribute(CategoryAttr);
MethodInfo GetValueMethod = null;
MethodInfo SetValueMethod = null;
Type GetReturnType = CLRType;
Type SetArgumentType = CLRType;
MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
BindingFlags MethodSearchFlags = BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public;
if (Type == ReflectedType.ARRAY)
{
GetReturnType = SetArgumentType = CLRType.GetGenericArguments()[0];
GetValueMethod = StorageType.GetMethod("get_Item", MethodSearchFlags, null, new Type[] { typeof(Int32) }, null);
SetValueMethod = StorageType.GetMethod("set_Item", MethodSearchFlags, null, new Type[] { typeof(Int32), SetArgumentType }, null);
}
else
{
GetValueMethod = StorageType.GetMethod("Get", MethodSearchFlags, null, new Type[] { typeof(Int32) }, null);
SetValueMethod = StorageType.GetMethod("Set", MethodSearchFlags, null, new Type[] { typeof(Int32), CLRType }, null);
}
//Build direct access for single values, basically just calls GetValue(0) or SetValue(0, value)
if (ArrayDim == 1 && Type != ReflectedType.ARRAY)
{
// Build get method
Debug.Assert(GetValueMethod != null);
MethodBuilder GetMethod = Builder.DefineMethod("get_" + Name, GetSetAttr, GetReturnType, System.Type.EmptyTypes);
ILGenerator GetOpCodes = GetMethod.GetILGenerator();
GetOpCodes.Emit(OpCodes.Ldarg_0); // push this
GetOpCodes.Emit(OpCodes.Ldfld, Field); // push field
GetOpCodes.Emit(OpCodes.Ldc_I4, 0); // push index of 0
GetOpCodes.Emit(OpCodes.Call, GetValueMethod); // call this.GetValue(0)
GetOpCodes.Emit(OpCodes.Ret); // return whatever that left on the stack
Prop.SetGetMethod(GetMethod);
// Build set method
Debug.Assert(SetValueMethod != null);
MethodBuilder SetMethod = Builder.DefineMethod("set_" + Name, GetSetAttr, null, new Type[] { SetArgumentType });
ILGenerator SetOpCodes = SetMethod.GetILGenerator();
SetOpCodes.Emit(OpCodes.Ldarg_0); // push this
SetOpCodes.Emit(OpCodes.Ldfld, Field); // push field
SetOpCodes.Emit(OpCodes.Ldc_I4, 0); // push index of 0
SetOpCodes.Emit(OpCodes.Ldarg_1); // push value
SetOpCodes.Emit(OpCodes.Call, SetValueMethod); // call this.SetValue(0, value)
SetOpCodes.Emit(OpCodes.Ret); // return
Prop.SetSetMethod(SetMethod);
}
else // Build array/indexed accessors
{
// Build get method
Debug.Assert(GetValueMethod != null);
MethodBuilder GetMethod = Builder.DefineMethod("get_" + Name, GetSetAttr, GetReturnType, new Type[] { typeof(int) });
ILGenerator GetOpCodes = GetMethod.GetILGenerator();
GetOpCodes.Emit(OpCodes.Ldarg_0); // push this
GetOpCodes.Emit(OpCodes.Ldfld, Field); // push field
GetOpCodes.Emit(OpCodes.Ldarg_1); // push index
GetOpCodes.Emit(OpCodes.Call, GetValueMethod); // call this.GetValue(index)
GetOpCodes.Emit(OpCodes.Ret); // return
Prop.SetGetMethod(GetMethod);
// Build set method
Debug.Assert(SetValueMethod != null);
MethodBuilder SetMethod = Builder.DefineMethod("set_" + Name, GetSetAttr, null, new Type[] { typeof(int), SetArgumentType });
ILGenerator SetOpCodes = SetMethod.GetILGenerator();
SetOpCodes.Emit(OpCodes.Ldarg_0); // push this
SetOpCodes.Emit(OpCodes.Ldfld, Field); // push field
SetOpCodes.Emit(OpCodes.Ldarg_1); // push index
SetOpCodes.Emit(OpCodes.Ldarg_2); // push value
SetOpCodes.Emit(OpCodes.Call, SetValueMethod); // call this.SetValue(index, value)
SetOpCodes.Emit(OpCodes.Ret); // return
Prop.SetSetMethod(SetMethod);
}
}
catch (System.Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
}
示例6: CreateConstructorAndDispatch
private static MethodBuilder CreateConstructorAndDispatch(DynamicTypeWrapper.FinishContext context, ClassFile.ConstantPoolItemInvokeDynamic cpi, TypeBuilder tb,
List<MethodWrapper> methods, TypeWrapper[] implParameters, ClassFile.ConstantPoolItemMethodType samMethodType, ClassFile.ConstantPoolItemMethodHandle implMethod,
ClassFile.ConstantPoolItemMethodType instantiatedMethodType, bool serializable)
{
TypeWrapper[] args = cpi.GetArgTypes();
// captured values
Type[] capturedTypes = new Type[args.Length];
FieldBuilder[] capturedFields = new FieldBuilder[capturedTypes.Length];
for (int i = 0; i < capturedTypes.Length; i++)
{
capturedTypes[i] = args[i].TypeAsSignatureType;
FieldAttributes attr = FieldAttributes.Private;
if (i > 0 || !args[0].IsGhost)
{
attr |= FieldAttributes.InitOnly;
}
capturedFields[i] = tb.DefineField("arg$" + (i + 1), capturedTypes[i], attr);
}
// constructor
MethodBuilder ctor = ReflectUtil.DefineConstructor(tb, MethodAttributes.Assembly, capturedTypes);
CodeEmitter ilgen = CodeEmitter.Create(ctor);
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Call, Types.Object.GetConstructor(Type.EmptyTypes));
for (int i = 0; i < capturedTypes.Length; i++)
{
ilgen.EmitLdarg(0);
ilgen.EmitLdarg(i + 1);
ilgen.Emit(OpCodes.Stfld, capturedFields[i]);
}
ilgen.Emit(OpCodes.Ret);
ilgen.DoEmit();
// dispatch methods
foreach (MethodWrapper mw in methods)
{
EmitDispatch(context, args, tb, mw, implParameters, implMethod, instantiatedMethodType, capturedFields);
}
// writeReplace method
if (serializable)
{
MethodBuilder writeReplace = tb.DefineMethod("writeReplace", MethodAttributes.Private, Types.Object, Type.EmptyTypes);
ilgen = CodeEmitter.Create(writeReplace);
context.TypeWrapper.EmitClassLiteral(ilgen);
ilgen.Emit(OpCodes.Ldstr, cpi.GetRetType().Name.Replace('.', '/'));
ilgen.Emit(OpCodes.Ldstr, cpi.Name);
ilgen.Emit(OpCodes.Ldstr, samMethodType.Signature.Replace('.', '/'));
ilgen.EmitLdc_I4((int)implMethod.Kind);
ilgen.Emit(OpCodes.Ldstr, implMethod.Class.Replace('.', '/'));
ilgen.Emit(OpCodes.Ldstr, implMethod.Name);
ilgen.Emit(OpCodes.Ldstr, implMethod.Signature.Replace('.', '/'));
ilgen.Emit(OpCodes.Ldstr, instantiatedMethodType.Signature.Replace('.', '/'));
ilgen.EmitLdc_I4(capturedFields.Length);
ilgen.Emit(OpCodes.Newarr, Types.Object);
for (int i = 0; i < capturedFields.Length; i++)
{
ilgen.Emit(OpCodes.Dup);
ilgen.EmitLdc_I4(i);
ilgen.EmitLdarg(0);
ilgen.Emit(OpCodes.Ldfld, capturedFields[i]);
if (args[i].IsPrimitive)
{
Boxer.EmitBox(ilgen, args[i]);
}
else if (args[i].IsGhost)
{
args[i].EmitConvSignatureTypeToStackType(ilgen);
}
ilgen.Emit(OpCodes.Stelem, Types.Object);
}
MethodWrapper ctorSerializedLambda = ClassLoaderWrapper.LoadClassCritical("java.lang.invoke.SerializedLambda").GetMethodWrapper(StringConstants.INIT,
"(Ljava.lang.Class;Ljava.lang.String;Ljava.lang.String;Ljava.lang.String;ILjava.lang.String;Ljava.lang.String;Ljava.lang.String;Ljava.lang.String;[Ljava.lang.Object;)V", false);
ctorSerializedLambda.Link();
ctorSerializedLambda.EmitNewobj(ilgen);
ilgen.Emit(OpCodes.Ret);
ilgen.DoEmit();
if (!context.TypeWrapper.GetClassLoader().NoAutomagicSerialization)
{
// add .NET serialization interop support
Serialization.MarkSerializable(tb);
Serialization.AddGetObjectData(tb);
}
}
return ctor;
}
示例7: DeclaringType
public void DeclaringType(TypeBuilder type, Type fieldType, FieldAttributes attributes)
{
FieldBuilder field = type.DefineField(fieldType.ToString(), fieldType, attributes);
Assert.Equal(type.AsType(), field.DeclaringType);
}