BindingFlags.OptionalParameterBinding different behavior in different frameworks. Error in .NET?

I tried to force Activator.CreateInstance use the constructor with default parameters.

I found this sentence repeated several times on SO (first comment) http://connect.microsoft.com/VisualStudio/feedback/details/521722/system-activator-createinstance-throws-system-missingmethodexception-with-constructor-containing- an-optional-parameter

I wanted to run it on Mono, and that didn't work, throwing a MissingMethodException . Before reporting the error, I did an experiment on .NET 4.5:

 class Program { static void Main(string[] args) { new A(); Activator.CreateInstance(typeof(A), BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance | BindingFlags.OptionalParamBinding, null, new Object[] {Type.Missing}, null); } } class A { public A() { Console.WriteLine("First"); } public A(int i = 5) { Console.WriteLine("Second"); } } 

Of course, the result was predictable:

 First Second 

Then I tried to remove the Type.Missing parameter to find out what would happen, hoping to find a way to invoke the constructor with a different number of default parameters.

I was stunned to see that nothing had changed! Skipping new Object[]{} , I expected:

 First First 

I wonder what Type.Missing does, and, according to golly !, why it is mentioned in the examples over the Internet, I changed the structure.

In .NET 4.0 everything was the same, BUT on .NET 3.5 the result was

 First First 

It seems very strange. Are there any documented reasons for this behavior?

What is the proper way to invoke a constructor with possibly a few optional parameters?

+4
source share

Source: https://habr.com/ru/post/1495752/


All Articles