简体   繁体   中英

Reflecting constructors with default values in C#4.0

I've just started using C#4.0(RC) and come up with this problem:

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

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. 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. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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