需要从ConstructorInfo获取可选参数

时间:2012-06-12 21:18:26

标签: c# c#-4.0 reflection

  

可能重复:
  Invoking methods with optional parameters through reflection
  Name of the constructor arguments in c#

现在我正在使用反射构建对象。我用它来填写API文档。在许多情况下,我想要一个非默认构造函数,但有时它们有可选参数。需要使用默认值以外的新对象覆盖这些可选参数。问题是我无法弄清楚如何获得它们。使用constructorInfo.GetParameters()可以很容易地使用普通参数,但是看起来可选的不会回来。我在这里错过了什么吗?

示例代码:

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

答案:事实证明他们确实回来了......这是用户错误。

样品:

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 = "")
    {
    }
}

输出:

名称:option1可选:False 名称:option2可选:True

2 个答案:

答案 0 :(得分:1)

可能重复。您似乎可以调用参数,但必须手动设置值。

我在这里发现了类似的问题:

Invoking methods with optional parameters through reflection

答案 1 :(得分:0)

看到这里,它有效:

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

public class Foo
{
    public Foo(string paramName)
    {   
    }
}
相关问题