【问题标题】:How to Load type from string directly into linq expression in C#?如何将字符串中的类型直接加载到 C# 中的 linq 表达式中?
【发布时间】:2011-02-04 19:00:11
【问题描述】:

这是定义:

public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source);

如何将 TResult 替换为:

Type.GetType("MyClass from assembly");

【问题讨论】:

    标签: c# linq string lambda types


    【解决方案1】:

    你不能。通用参数在编译时强制执行类型安全,而 Type.GetType 使用反射并且在编译时未知。你到底想达到什么目的?

    【讨论】:

    【解决方案2】:

    如果您不知道所涉及的类型,则无法在编译时执行此操作,但您可以为 IEnumerable 编写自己的扩展方法:

    public static IEnumerable OfType(this IEnumerable source, Type t)
    {
        foreach(object o in source)
        {
            if(t.IsAssignableFrom(o.GetType()))
                yield return o;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-25
      • 2021-09-29
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多