繁体   English   中英

在泛型类型的构造函数中使用C#params关键字

[英]Using C# params keyword in a constructor of generic types

我在C#中有一个带有2个构造函数的泛型类:

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

使用int作为泛型类型构造对象并传入两个int作为参数会导致调用“不正确”的构造函数(从我的角度来看)。

例如Houses<int> houses = new Houses<int>(1,2) - 调用第二个construtor。 将任何其他数量的int传递给构造函数将调用第一个构造函数。

除了删除params关键字并强制用户在使用第一个构造函数时传递T数组,还有什么方法吗?

更清晰的解决方案是拥有两种静态工厂方法。 如果将这些放入非泛型类中,您还可以从类型推断中受益:

public static class Houses
{
    public static Houses<T> CreateFromElements<T>(params T[] initialElements)
    {
        return new Houses<T>(initialElements);
    }

    public Houses<T> CreateFromDefault<T>(int count, T defaultValue)
    {
        return new Houses<T>(count, defaultValue);
    }
}

调用示例:

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

然后你的泛型类型的构造函数不需要“params”位,并且不会有混淆。

也许代替Params你可以传入IEnumerable

public Houses(IEnumerable<T> InitialiseElements){}

第二个构造函数是一个更精确的匹配,这是用于评估哪个构造函数是正确的标准。

考虑到以下因为原来没有太多关于班级等的信息。

编译器将决定新的House(1,2)与第二个构造函数完全匹配并使用它,注意我用最多的投票得到了答案而且它没有用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericTest
{
    public class House<T>
    {
        public House(params T[] values)
        {
            System.Console.WriteLine("Params T[]");
        }
        public House(int num, T defaultVal)
        {
            System.Console.WriteLine("int, T");
        }

        public static House<T> CreateFromDefault<T>(int count, T defaultVal)
        {
            return new House<T>(count, defaultVal);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            House<int> test = new House<int>(1, 2);                         // prints int, t
            House<int> test1 = new House<int>(new int[] {1, 2});            // prints parms
            House<string> test2 = new House<string>(1, "string");           // print int, t
            House<string> test3 = new House<string>("string", "string");    // print parms
            House<int> test4 = House<int>.CreateFromDefault<int>(1, 2);     // print int, t
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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