1

可能重复:
通过反射调用带有可选参数的方法
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

4

2 回答 2

1

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

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

通过反射调用带有可选参数的方法

于 2012-06-12T21:38:24.697 回答
0

看这里,它有效:

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

public class Foo
{
    public Foo(string paramName)
    {   
    }
}
于 2012-06-12T21:28:52.560 回答