简体   繁体   中英

Reflection for Constructors

Here:

defaultCon binds itself to Dog() Constructor

legCon binds itself to Dog(int legs) Constructor

Why do we specify

new Type[0] in Line X even though there are no parameters in Default Constructor

(new[] { typeof(int) }) in Line Y ! Curly braces inside argument/parameter field.Similar problem in Line Z.

I searched on StackOverflow - this answer came close but doesn't answer my question. Here is my code:

namespace Coding
{
    internal class Dog
    {
        public int NumberOfLegs { get; set; }
        public Dog()
        {
            NumberOfLegs = 4;
        }

        public Dog(int legs)
        {
            NumberOfLegs = legs;
        }
    }

    public class Class1
    {
        static void Main(string[] args)
        {
            /*line X*/  var defaultCon = typeof(Dog).GetConstructor(new Type[0]); // Get Default Constructor without any params
            /*line Y*/  var legCon = typeof(Dog).GetConstructor(new[] { typeof(int) });//get constructor with param int

            var defaultDog = defaultCon.Invoke(null) as Dog;//invoke defaultCon for a Dog Object
            /*Line Z*/  var legDog = legCon.Invoke(new object[] { 5 });//invoke legCon for a Dog object(Sets number of legs as 5) as Dog

            Console.Read();
        }
    }
}

Why do we specify "new Type[0]" in Line X even though there are no parameters in Default Constructor

To say that there are no parameters - so the array of parameter types is empty.

Why do we specify "(new[] { typeof(int) })" in Line Y! Curly braces inside argument/parameter field.

To create an array or parameter types with a single element - the type corresponding to int .

Similar problem in Line Z.

Same answer, except this time you're creating an array of arguments, instead of parameter types.

The simplest overload of Type.GetConstructor still takes an array of types to indicate the parameters of the constructor you're trying to get.

The value Type[0] is an empty array , which indicates no parameters.

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