You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#方法中传递并实例化泛型类型?

问题:C#泛型方法中如何实例化带参数的类型T?

我希望遵循DRY原则简化以下重复的方法(实际场景中还有更多类似的列表获取方法):

public static List<Genre> GetGenres(ApiCredentials apiCredentials = null, ApiServerParameters apiServerParameters = null)
{
    List<Genre> returns = new List<Genre>();

    GetData getData = new GetData(apiCredentials, apiServerParameters);
    var outcome = getData.GetListOrInfo(Enums.ApiQueryType.GenreList);

    XDocument xdoc = XDocument.Parse(outcome.Data.ToString());
    
    foreach (var genre in xdoc.Descendants("genre"))
    {
        returns.Add(new Genre(genre));
    }       

    return returns;
}

public static List<Language> GetLanguages(ApiCredentials apiCredentials = null, ApiServerParameters apiServerParameters = null)
{
    List<Language> returns = new List<Language>();

    GetData getData = new GetData(apiCredentials, apiServerParameters);
    var outcome = getData.GetListOrInfo(Enums.ApiQueryType.LanguageList);

    XDocument xdoc = XDocument.Parse(outcome.Data.ToString());

    foreach (var language in xdoc.Descendants("langue"))
    {
        returns.Add(new Language(language));
    }

    return returns;
}

我尝试用泛型T重构,但无法直接实例化T(编译报错):

public static List<T> GetList<T>(Enums.ApiQueryType queryType, string xElementName,
    ApiCredentials apiCredentials = null, ApiServerParameters apiServerParameters = null)
{

    List<T> returns = new List<T>();

    GetData getData = new GetData(apiCredentials, apiServerParameters);
    var outcome = getData.GetListOrInfo(queryType);

    XDocument xdoc = XDocument.Parse(outcome.Data.ToString());

    foreach (var element in xdoc.Descendants(xElementName))
    {
        returns.Add(new T(element)); /// 此处编译失败
    }

    return null;
}

请问该如何实现泛型T的实例化?


解决方案

可以通过Activator.CreateInstance反射创建带参数的T实例,重构后的正确泛型方法如下:

public static List<T> GetList<T>(Enums.ApiQueryType queryType, string xElementName,
    ApiCredentials apiCredentials = null, ApiServerParameters apiServerParameters = null)
{

    List<T> returns = new List<T>();

    GetData getData = new GetData(apiCredentials, apiServerParameters);
    var outcome = getData.GetListOrInfo(queryType);

    XDocument xdoc = XDocument.Parse(outcome.Data.ToString());

    foreach (var element in xdoc.Descendants(xElementName))
    {
        var obj = (T)Activator.CreateInstance(typeof(T), element);
        returns.Add(obj);
    }

    return returns;
}

内容的提问来源于stack exchange,提问作者stigzler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:15:18