samedi 29 juillet 2017

ParameterInfo.DefaultValue returns null for value type

I have the following method signature:

static void SetControlSprite(string ctrlName, Sprite spr, Color color = default(Color))

Color is a standard simple RGBA struct type, that is roughly this:

public struct Color
{
    public float r;
    public float g;
    public float b;
    public float a;
}

When using reflection get the last ParameterInfo, for color, I get the following results:

parameterInfo.HasDefaultValue == true

parameterInfo.Defaultvalue == null

I was expecting DefaultValue to be a Color object with all values at zero. I don't see anywhere in MSDN a mention of value type parameters returning null default values.

The workaround is simple, but I'm surprised that I need it:

var defaultValue = parameterInfo.DefaultValue;

if (defaultValue == null && parameterInfo.ParameterType.IsValueType)
{
    defaultValue = Activator.CreateInstance(parameterInfo.ParameterType);
}

Is this normal? Is it documented anywhere?





Aucun commentaire:

Enregistrer un commentaire