Necesita obtener parámetros opcionales de ConstructorInfo [duplicado]

Posible duplicado:
Invocar métodos con parámetros opcionales a través de la reflexión
Nombre de los argumentos del constructor en c #

Right now I am constructing objects using reflection. I am using this to fill out API documentation. In many cases I want a non-default constructor, but sometimes they have optional parameters. These optional parameters need to be overridden with a new object other than the default. The problem is I cant figure out how to get them. The normal parameters are easy with constructorInfo.GetParameters(), however it seems the optional do not come back. Am I missing something here?

Código de muestra:

            ConstructorInfo[] constructorInfoList = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
            foreach (ConstructorInfo constructorInfo in constructorInfoList)
            {
                var parameters = constructorInfo.GetParameters();
                if (parameters.Count() > 0)
                {

Answer: It turns out they do come back... this was user error.

Muestra:

void Main()
{
    var ctors = typeof(Foo).GetConstructors();
    foreach(var ctor in ctors)
    {
        foreach(var param in ctor.GetParameters())
        {
            Console.WriteLine("Name: {0} Optional: {1}", param.Name, param.IsOptional);
        }
    }   
}

public class Foo
{
    public Foo(string option1, string option2 = "")
    {
    }
}

Salida:

Name: option1 Optional: False Name: option2 Optional: True

preguntado el 12 de junio de 12 a las 22:06

I believe you mean "optional" and not "named." msdn.microsoft.com/en-us/library/dd264739.aspx -

Are you talking about attribute properties? -

Can you give an example of (the code of) a constructor for which constructorInfo.GetParameters() does not give you the information you want? -

yes optional, not named sorry. -

2 Respuestas

Possible duplicate. It appears that you can call the parameter, but have to set the values manually.

Encontré un problema similar aquí:

Invocar métodos con parámetros opcionales a través de la reflexión

contestado el 23 de mayo de 17 a las 13:05

Tom, thanks for the links. It turned out that I was Reflecting over 2 classes named the same thing, one had them and one didnt... I didnt write all this code, so I had no clue this could have been the case. The optional params do come back, and they do have an attribute that marks them. Again, thanks. - dardoloco

See here, it works:

var parameterName =
    typeof(Foo)
    .GetConstructor(new[] { typeof(string) })
    .GetParameters()
    .Single().Name;

public class Foo
{
    public Foo(string paramName)
    {   
    }
}

Respondido el 12 de junio de 12 a las 22:06

I tried also with optionals parameters, FW 4.0, it works. - Mateo Migliore

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.