Using C# params keyword in a constructor of generic types

前端 未结 4 967
后悔当初
后悔当初 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:12

    A clearer solution would be to have two static factory methods. If you put these into a nongeneric class, you can also benefit from type inference:

    public static class Houses
    {
        public static Houses CreateFromElements(params T[] initialElements)
        {
            return new Houses(initialElements);
        }
    
        public Houses CreateFromDefault(int count, T defaultValue)
        {
            return new Houses(count, defaultValue);
        }
    }
    

    Example of calling:

    Houses x = Houses.CreateFromDefault(10, "hi");
    Houses y = Houses.CreateFromElements(20, 30, 40);
    

    Then your generic type's constructor doesn't need the "params" bit, and there'll be no confusion.

提交回复
热议问题