jeudi 23 juillet 2015

GetType() of an empty string variable

I'm using reflection to call a static, generic method (as the type is only known at runtime). This seems to be working well for me, until the type is of string. I get an "Object not set to an instance of the object" exception on Type proptype = entity[property.Key].GetType(); in the code below. I believe it is because at the time that it's getting the type, the string is empty.

            foreach (KeyValuePair<string, FieldAttribute> property in EntityProperties)
            {
                Type gen = typeof(DBGeneric);
                MethodInfo mi = gen.GetMethod("FromDBVal");

                Type proptype = entity[property.Key].GetType();

                MethodInfo mil = mi.MakeGenericMethod(proptype);

                object[] args = { dr[property.Value.ColumnName] };
                entity[property.Key]=mil.Invoke(null, args);
            }

dr is a datareader. EntityProperties is a dictionary populated using reflection earlier, to avoid unnecessary, repeat reflection. FieldAttribute is a custom attribute on each property of the model that specifies how that property relates back to the column of the table in the database. Here are two example properties:

    [Field("COLUMN1", "Description of this column.", true)]
    public int Property1 { get; set; }

    [Field("COLUMN2", "Description of this column.", true)]
    public string Property2 { get; set; }

The generic method I'm calling, FromDBVal<T>, mostly just handles null values in the database, but also handles some types a little differently (due to the database design, sometimes some values will be returned as decimal with a precision of .00 when they should be int32.

So can anyone see a way I can get the type where it is an empty string?





Aucun commentaire:

Enregistrer un commentaire