簡體   English   中英

在C#中實例化泛型類型的實例

[英]Instantiate an instance of a generic type in C#

我有一個專門的通用集合類,它將用於保存許多不同類型的對象的集合。 創建集合后,我需要實例化集合的項目。 我有最迫切的時間讓它工作。 我必須缺少一個簡單的解決方案。

這是一個示例類,用於說明我正在嘗試執行的操作以及遇到的警告/錯誤。

// Note: T may either a string or other reference type that supports IEnumerable. 
public class Foo<T>
{
    private List<T> fooBarList = new List<T>();

    public Foo()
    {
        Bar1<T>();
        Bar2<T>();
        Bar3<T>();
    }

    public void Bar1<T>()
    {
        // Error Message: Argument 1 cannot convert from 'T...' to 'T...'
        T t = default;
        fooBarList.Add(t);
    }

    public void Bar2<T>() where T : IEnumerable, new()
    {
        // Error Message: T must be a non-abstract type with public
        // parameterless constructor in order to use it as a parameter 'T'
        // in the generic type or method 'Foo<T>.Bar2<T>()

        fooBarList.Add(new T());
    }

    public void Bar3<T>() where T : IEnumerable, new()
    {
        // Error Message: Argument 1 cannot convert from 'T...' to 'T...'
        T t = Activator.CreateInstance<T>();
        fooBarList.Add(t);
    }
}

旁注:此特定代碼在我的應用程序中對性能至關重要的部分中-您知道,3%的Donald Knuth談到需要進行實際優化。 這確實需要快速,因為每個應用程序執行將被調用數百萬次。 如果有其他選擇,我對使用反射(例如此處的Activator.CreateInstance())一點也不熱心。 (就目前而言,即使對於我來說似乎也不起作用。)我寧願讓編譯器在編譯時解析數據類型。

下面的鏈接中已經回答了這個問題,但是似乎沒有一種方法對我有用。 我想念什么?

在C#中,如何實例化方法內部傳遞的泛型類型?

僅供參考,我正在運行Visual Studio 2019企業預覽版的Windows 10計算機上使用.NET Core 2.2 Beta和.NET Standard 2.0。

似乎List<T>已經擁有您所需的全部內容,只是創建新實例並添加它的方法,可以將其添加為擴展方法:

public static ICollectionExtensions
{
    public static AddNew<T>(this ICollection<T> collection)
        where T : new()
    {
        var newItem = new T();
        collection.Add(newItem);
    }

    ...
} 

可以這樣使用:

var list = new List<int>();
list.AddNew();

這樣編譯:

public class Foo<T> where T : IEnumerable, new()
{
    private List<T> fooBarList = new List<T>();

    public Foo()
    {
        Bar1();
        Bar2();
        Bar3();
    }

    public void Bar1()
    {
        T t = default(T);
        fooBarList.Add(t);
    }

    public void Bar2()
    {
        fooBarList.Add(new T());
    }

    public void Bar3() 
    {
        T t = Activator.CreateInstance<T>();
        fooBarList.Add(t);
    }
}

請注意, T的唯一聲明是在類級別上的,包括<T>部分和where部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM