【问题标题】:Dynamic List Creation based on given object type in C#C#中基于给定对象类型的动态列表创建
【发布时间】:2014-08-22 13:26:30
【问题描述】:

我相当肯定这是可能的,而且我认为这很简单,只是我不知道在 Google 中提问的正确方法。我想要做的是将type 传递给一个方法并返回该类型的对象列表。像这样:

public List<T> GetComponentsOfType(Type thisType)
{
    return Components.OfType<thisType>().ToList();
}

这当然不会编译,因为我不知道自己在做什么。

【问题讨论】:

    标签: c# list generics types


    【解决方案1】:

    我猜你想传入类型参数,这样你就可以得到类型化的列表:

    public List<T> GetComponentsOfType<T>()
    {
        return Components.OfType<T>().ToList();
    }
    

    【讨论】:

    • 谢谢!我是如此接近。 =) -- 你知道这里的技术术语是什么,即我可以在谷歌中搜索什么来找到这个答案吗?
    • 我找到的第一个有效的是method pass in type return c#。首先但很不错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2017-07-19
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多