使用泛型参数而不是显式调用构造函数

Jan*_*kke 4 c# generics constructor

我认为这个问题是重复的.但我在SO上找不到这个问题

我想实例化一个泛型类.但是如果存在具有显式参数的构造函数并且由于给定类型,泛型构造函数也具有该参数,则使用具有显式参数的构造函数.

 class Program
 {
    static void Main(string[] args)
    {
       Example<string> test = new Example<string>("test");
       test.Print();//Prints test2
    }
 }

 class Example<T>
 {
    private object Value;

    public Example(T value1)
    {
       this.Value = value1 + "1";
    }

    public Example(string value2)
    {
       this.Value = value2 + "2";
    }

    public void Print()
    {
       Console.WriteLine(Value as string);
    }
 }
Run Code Online (Sandbox Code Playgroud)

有没有办法调用泛型构造函数?

Raj*_*gaj 5

您可以使用以下语法和命名参数:

Example<string> test = new Example<string>(value1: "test");

这里的重要技巧是拥有您当前拥有的不同参数名称,因此它将从参数名称映射正确的构造函数,代码将如下所示:

using System;

public class Program
{
   public static void Main()
   {
      Example<string> test = new Example<string>(value1: "test");
      test.Print();//Prints test1
   }

class Example<T>
{
    private object Value;

    public Example(T value1)
    {
       this.Value = value1 + "1";
    }

    public Example(string value2)
    {
        this.Value = value2 + "2";
    }

    public void Print()
    {
          Console.WriteLine(Value as string);
       }
    }   
}
Run Code Online (Sandbox Code Playgroud)

您也可以在这里找到有关命名参数的文档.