简体   繁体   English

使用C#4.0中的默认值反映构造函数

[英]Reflecting constructors with default values in C#4.0

I've just started using C#4.0(RC) and come up with this problem: 我刚开始使用C#4.0(RC)并提出了这个问题:

class Class1 { public Class1() { } }
class Class2 { public Class2(string param1) { } }
class Class3 { public Class3(string param1 = "default") { } }

Type[] types = new Type[] { typeof(Class1), typeof(Class2), typeof(Class3) };

// Problem starts here, main-method
for(int i = 0; i < types.Length; i++)
{
    ConstructorInfo ctr = provider.GetConstructor(Type.EmptyTypes);
    Console.WriteLine(ctr == null ? "null" : ctr.Name);
}

Note, I've never tried this actual code, but I've just looked at the results of doing GetConstructor using debugging in VS2010 注意,我从来没有尝试过这个实际的代码,但我刚刚看了一下在VS2010中使用调试来做GetConstructor的结果

This is perfect for the two first classes (1 and 2), the first one prints an actual ConstructorInfo-object's name of the parameterless constructor of Class1, the second prints null. 这对于两个第一类(1和2)是完美的,第一个类打印Class1的无参数构造函数的实际ConstructorInfo对象的名称,第二个类打印为null。 However, the problem arises with the third one, because what I actually want isn't to know whether it takes 0 parameters or not, but it's whether I can create an instance of the class without any parameters. 然而,问题出现在第三个问题上,因为我真正想要的是不知道它是否需要0个参数,但是我是否可以创建一个没有任何参数的类的实例。 How do I do that? 我怎么做?

I found a way to do it. 我找到了办法。 It's not pretty but it works. 它不漂亮,但它的工作原理。

var ctrs = from c in provider.GetConstructors()
           where c.GetParameters().Where(p => !p.IsOptional).Count() == 0
           select c;
ConstructorInfo ctr = ctrs.FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM