Create a class dynamically with Reflection.Emit. I got stuck

前端 未结 1 1990
醉梦人生
醉梦人生 2021-02-14 20:01

A read about creating types at runtime and i found it amazing. My goal is to create this class:

[DelimitedRecord(\",\")]
public class Person
{
    [FieldOrder(0         


        
1条回答
  •  灰色年华
    2021-02-14 20:55

    I made it work:

    //create the Delimiter attribute
    Type[] attributeParams = new Type[] { typeof(string) };
    ConstructorInfo classCtorInfo = typeof(DelimitedRecordAttribute).GetConstructor(attributeParams);
    CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(classCtorInfo, new object[] { ";" });
    typeBuilder.SetCustomAttribute(attributeBuilder);
    

    This would do the job for the field attributes:

    //create the firstName attribute [FieldOrder(0)]
    Type[] firstNameFieldOrderAttributeParams = new Type[] { typeof(int) };
    ConstructorInfo firstNameFieldOrderAttrInfo = typeof(FieldOrderAttribute).GetConstructor(firstNameFieldOrderAttributeParams);
    CustomAttributeBuilder firstNameFieldOrderAttributeBuilder = new CustomAttributeBuilder(firstNameFieldOrderAttrInfo, new object[] { 0 });
    firstNameField.SetCustomAttribute(firstNameFieldOrderAttributeBuilder);
    

    0 讨论(0)
提交回复
热议问题