Using C# params keyword in a constructor of generic types

前端 未结 4 983
后悔当初
后悔当初 2021-02-14 20:42

I have a generic class in C# with 2 constructors:

public Houses(params T[] InitialiseElements)
{}
public Houses(int Num, T DefaultValue)
{}

Con

4条回答
  •  春和景丽
    2021-02-14 21:02

    Given the following since the original did not have too much information on the class etc.

    The compiler is going to decide new House(1,2) matches the second constructor exactly and use that, notice that I took the answer with the most up votes and it did not work.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GenericTest
    {
        public class House
        {
            public House(params T[] values)
            {
                System.Console.WriteLine("Params T[]");
            }
            public House(int num, T defaultVal)
            {
                System.Console.WriteLine("int, T");
            }
    
            public static House CreateFromDefault(int count, T defaultVal)
            {
                return new House(count, defaultVal);
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                House test = new House(1, 2);                         // prints int, t
                House test1 = new House(new int[] {1, 2});            // prints parms
                House test2 = new House(1, "string");           // print int, t
                House test3 = new House("string", "string");    // print parms
                House test4 = House.CreateFromDefault(1, 2);     // print int, t
            }
        }
    }
    

提交回复
热议问题