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

时间:2017-05-29 20:17:35

标签: 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);
    }
 }

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

1 个答案:

答案 0 :(得分:5)

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

(Chat.py:61330): Gdk-ERROR **: The program 'Chat.py' received an X Window System error. This probably reflects a bug in the program. The error was 'BadRequest (invalid request code or no such operation)'. (Details: rerial 892 error_code 1 request_code 0 (core protocol) minor_code 0) (Note to programmers: normally, X errors are reported asynchronously; that is, you will receive the error a while after causing it. To debug your program, run it with the GDK_SYNCHRONIZE environment variable to change this behavior. You can get a meaningful backtrace from your debugger if you break on the gdk_x_error() function.) Trace/BPT trap (code dumped)

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

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

您也可以找到有关命名参数的here文档。