mardi 4 août 2015

C# Fill a class with test data

I'm using reflection to fill a given C# class with test data

public object CreateObj(Type type)
{
    var obj = Activator.CreateInstance(type);
    var fields = type.GetFields();
    foreach (var field in fields)
    {
        field.SetValue(obj, GetRnd(field.FieldType));
    }

    return obj;
}

The GetRnd() function set the value according to the type of the field:

private object GetRnd(Type type)
{
    if (type == typeof(int))
    {
        return 4;
    }
    else if (type == typeof(string))
    {
        return "text";
    }
    else
    {
        throw new Exception();
    }

}

This works as long as I pass to CreateObj() a proper class. I'd like to make it work even with basic types (string, int and so on..) By now I get a "SetType(): Cannot set a constant field" exception when I pass a simple "int".

Aucun commentaire:

Enregistrer un commentaire