How can I set constant value to an enum field when creating a new enum #922

Open
opened 2023-08-10 11:34:07 -05:00 by SwingCosmic · 0 comments
SwingCosmic commented 2023-08-10 11:34:07 -05:00 (Migrated from github.com)

I can't set value to FieldDefinition.Constant and FieldDefinition.HasConstant because it depends on the constant value inside of the assembly module.

private TypeDefinition CloneEnum(TypeDefinition type,  ModuleDefinition target)
{
    var baseType = target.ImportReference(typeof(Enum));
    var newEnum = new TypeDefinition(type.Namespace, type.Name, type.Attributes, baseType);

    Console.WriteLine(type.Name);
    foreach (var f in type.Fields)
    {
        FieldDefinition field;
        if (!f.HasConstant) // value__
        {
            field = new FieldDefinition(f.Name, f.Attributes, target.TypeSystem.Int32);
        } else
        {
            field = new FieldDefinition(f.Name, f.Attributes, newEnum);
            // next two lines doesn't work
            field.HasConstant = true; //still false
            field.Constant = f.Constant; // still null
        }
        newEnum.Fields.Add(field);
    }
    return newEnum;
}

The result assembly contains the enums without any values.

image

And I'am really confused about this two properties:

image

image

I can't set value to `FieldDefinition.Constant` and `FieldDefinition.HasConstant` because it depends on the constant value inside of the assembly module. ```csharp private TypeDefinition CloneEnum(TypeDefinition type, ModuleDefinition target) { var baseType = target.ImportReference(typeof(Enum)); var newEnum = new TypeDefinition(type.Namespace, type.Name, type.Attributes, baseType); Console.WriteLine(type.Name); foreach (var f in type.Fields) { FieldDefinition field; if (!f.HasConstant) // value__ { field = new FieldDefinition(f.Name, f.Attributes, target.TypeSystem.Int32); } else { field = new FieldDefinition(f.Name, f.Attributes, newEnum); // next two lines doesn't work field.HasConstant = true; //still false field.Constant = f.Constant; // still null } newEnum.Fields.Add(field); } return newEnum; } ``` The result assembly contains the enums without any values. ![image](https://github.com/jbevain/cecil/assets/20746516/a9737476-5b5f-4d2c-a189-d189bddd048f) And I'am really confused about this two properties: ![image](https://github.com/jbevain/cecil/assets/20746516/4f6d532c-621c-41ea-8df3-fcc6948650f4) ![image](https://github.com/jbevain/cecil/assets/20746516/0185c4b2-88a9-485d-861b-96b60329f491)
Sign in to join this conversation.
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
gh-jbevain/cecil#922
No description provided.