How to create a class dynamicaly

blfuentes

I am trying to generate a class dinamicaly through a List of dictionaries with the following code:

public static object CreateCustomObject(List<Dictionary<string, string>> fileProperties)
{
    object result = null;
    
    // create the assembly and module
    AssemblyName assemblyName = new AssemblyName();
    assemblyName.Name = "tmpAssembly";
    AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
    ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpAssembly");
    
    // create a new type builder
    TypeBuilder typeBuilder = module.DefineType("CustomObjectToSerialize", TypeAttributes.Public | TypeAttributes.Class);
    
    foreach (Dictionary<string, string> _property in fileProperties)
    {
        foreach (var _elem in _property)
        {
            // create property from file      
            string propertyName = _elem.Key.Replace('.', '_');
            FieldBuilder field = typeBuilder.DefineField("_" + propertyName, typeof(string), FieldAttributes.Private);
            PropertyBuilder property = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, typeof(string), new Type[] { typeof(string) });
    
            MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig;
    
            MethodBuilder currGetPropMethBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, typeof(string), Type.EmptyTypes);
    
            ILGenerator currGetIL = currGetPropMethBldr.GetILGenerator();
            currGetIL.Emit(OpCodes.Ldarg_0);
            currGetIL.Emit(OpCodes.Ldfld, field);
            currGetIL.Emit(OpCodes.Ret);
    
            MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, typeof(string), Type.EmptyTypes);
    
            ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
            currSetIL.Emit(OpCodes.Ldarg_0);
            currSetIL.Emit(OpCodes.Ldarg_1);
            currSetIL.Emit(OpCodes.Stfld, field);
            currSetIL.Emit(OpCodes.Ret);
    
            property.SetGetMethod(currGetPropMethBldr);
            property.SetSetMethod(currSetPropMthdBldr);
        }
    }
    
    Type generatedType = typeBuilder.CreateType();
    result = Activator.CreateInstance(generatedType);
    PropertyInfo[] properties = generatedType.GetProperties();
    
    int propertiesCount = 0;
    
    List<string> values = new List<string>();
    foreach (Dictionary<string, string> _property in fileProperties)
    {
        foreach (var _elem in _property)
        {
            //values.Add(_elem.Value);
            string value = _elem.Value;
            string propName = _elem.Key.Replace('.', '_');
            PropertyInfo pinfo = generatedType.GetProperty(propName);
            //here I get the error
            //'System.Reflection.TargetParameterCountException' occurred in mscorlib.dll
            pinfo.SetValue(result, value);
            //properties[propertiesCount].SetValue(result, value, null);
            //propertiesCount++;
        }
    }
    
    //values.ForEach(_v =>
    //{
    //   properties[propertiesCount].SetValue(result, _v, null);
    //   propertiesCount++;
    //});
    
    return result;
}

I get this error when trying to set the value of the property.:

An unhandled exception of type 'System.Reflection.TargetParameterCountException' occurred in mscorlib.dll Additional information: Parameter count mismatch.

I checked and I have in my sample 3 properties and I will assign 3 values.

The code is taken and Little bit adapted from here

Any idea?

Peter Duniho

You have defined the setter method incorrectly. You seem to have copy/pasted from the getter, without correctly modifying the return type and argument list.

While the getter returns a value and has no arguments, a setter returns no value (i.e. is void) and takes one argument.

Instead of what you have in your code, it should look like this:

MethodBuilder currSetPropMthdBldr =
    typeBuilder.DefineMethod("set_value", GetSetAttr, null, new [] { typeof(string) });

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Create method dynamicaly in Groovy with arguments

From Dev

Create method dynamicaly in Groovy with arguments

From Dev

Meteor create new template dynamicaly

From Dev

How to bring dynamicaly scope in view

From Dev

How to use update cursor dynamicaly

From Dev

Dynamicaly add methods from outside the class with a decorator

From Dev

Add active class dynamicaly not working properly

From Dev

Dynamicaly instanciate class from name with injector

From Dev

TypeScript: Create union type dynamicaly from interface

From Dev

How to change name in context menu dynamicaly by a condition

From Dev

How to get black shadow around the image dynamicaly?

From Dev

How to Invoke dynamicaly an anonymus objects function property?

From Dev

How to handle permission and controllers dynamicaly in laravel

From Dev

How to change name in context menu dynamicaly by a condition

From Dev

How to add a tooltip on inputbox dynamicaly in angular 2

From Dev

Dynamicaly change class name of same class by adding number

From Dev

How to Create a Disposable class

From Dev

How to create class with comparator?

From Dev

How to add custom layout to linear layout in scrollView dynamicaly

From Dev

QML,How to dynamicaly change Item of Repeater from C++

From Dev

How can I change dynamicaly the opacity of a linegraph in D3?

From Dev

Angular: understanding how DI works in dynamicaly loaded component

From Dev

QML,How to dynamicaly change Item of Repeater from C++

From Dev

How to dynamicaly load and save user settings in WPF multi window application?

From Dev

How to create an instance of an imported class in another class

From Dev

How to pass a class and method to create an instance of a class?

From Dev

How to create a class that will be under of a class in solution explorer?

From Dev

How to create Mock to a class that implement an abstract class

From Dev

How to create a smartpointer to a class and initialize the class constructor

Related Related

  1. 1

    Create method dynamicaly in Groovy with arguments

  2. 2

    Create method dynamicaly in Groovy with arguments

  3. 3

    Meteor create new template dynamicaly

  4. 4

    How to bring dynamicaly scope in view

  5. 5

    How to use update cursor dynamicaly

  6. 6

    Dynamicaly add methods from outside the class with a decorator

  7. 7

    Add active class dynamicaly not working properly

  8. 8

    Dynamicaly instanciate class from name with injector

  9. 9

    TypeScript: Create union type dynamicaly from interface

  10. 10

    How to change name in context menu dynamicaly by a condition

  11. 11

    How to get black shadow around the image dynamicaly?

  12. 12

    How to Invoke dynamicaly an anonymus objects function property?

  13. 13

    How to handle permission and controllers dynamicaly in laravel

  14. 14

    How to change name in context menu dynamicaly by a condition

  15. 15

    How to add a tooltip on inputbox dynamicaly in angular 2

  16. 16

    Dynamicaly change class name of same class by adding number

  17. 17

    How to Create a Disposable class

  18. 18

    How to create class with comparator?

  19. 19

    How to add custom layout to linear layout in scrollView dynamicaly

  20. 20

    QML,How to dynamicaly change Item of Repeater from C++

  21. 21

    How can I change dynamicaly the opacity of a linegraph in D3?

  22. 22

    Angular: understanding how DI works in dynamicaly loaded component

  23. 23

    QML,How to dynamicaly change Item of Repeater from C++

  24. 24

    How to dynamicaly load and save user settings in WPF multi window application?

  25. 25

    How to create an instance of an imported class in another class

  26. 26

    How to pass a class and method to create an instance of a class?

  27. 27

    How to create a class that will be under of a class in solution explorer?

  28. 28

    How to create Mock to a class that implement an abstract class

  29. 29

    How to create a smartpointer to a class and initialize the class constructor

HotTag

Archive