【问题标题】:IEnumerable<T> generics - "Cannot find symbol" inside method (T is passed by the calling function)IEnumerable<T> 泛型 - 方法内部“找不到符号”(T 由调用函数传递)
【发布时间】:2014-10-21 14:46:26
【问题描述】:

我正在尝试使用 IEnumerable 泛型。我在调用相应方法时从另一个文件传递数据类型。但是当使用 are 过滤 IEnumerable 时,我收到错误“未定义符号”,因为 IEnumerable 方法是在运行时传递的。

public IEnumerable<T> FetchData<T>(int take, int skip, string guidRelatedA, string guidRelatedB, bool filterA, bool filterB, IEnumerable<T> dataToFilter)
{
    if (filterA && filterB)
    {
        var  query = from p in dataToFilter
                     .Where(o => (o.FilterA.Any(f => f.Id.ToString().Equals(guidRelatedA))) &&
                                 (o.FilterB.Any(f => f.Id.ToString().Equals(guidRelatedB))))
                     .Take(take)
                     .Skip(skip)
                     select p;
        return query;
     } 
}

FilterAFilterB 给我一个错误,FilterA 和 FilterB 对我使用的所有类都是通用的,有什么解决方法可以克服这个问题吗?

【问题讨论】:

  • 你能保证T 是一个具有FilterAFilterB 属性的类吗?
  • 因为它是T 绝对可以是任何东西。您需要使用约束来限制 T 可以是什么。见:msdn.microsoft.com/en-us/library/d5x73970.aspx
  • 请修正您的代码缩进。
  • 在我的 pgm 中是的,我可以..!!
  • 谢谢@MattBurland,解决了我的问题:)

标签: c# asp.net generics ienumerable


【解决方案1】:

听起来您需要为 T 添加一个约束,其中 T : 基类或接口。

类似

public interface IFilterable 
{
   object FilterA {get; set;}
   object FilterB {get; set;}
}

public IEnumerable<T> FetchData<T>(int take, int skip, string guidRelatedA, string guidRelatedB, bool filterA,
                             bool filterB, IEnumerable<T> dataToFilter) where T : IFilterable
{
...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多