简体   繁体   English

可能限制通用方法的输出?

[英]possible to constrain output in generic method?

I have an interface which defines various filtering on data (queries coming from EF4). 我有一个接口,该接口定义了对数据的各种过滤(来自EF4的查询)。

Interface method: 接口方式:

IQueryable<T> filter<T>() where T : class;

Now in a concrete implementation of that interface, I want to be able to do: 现在,在该接口的具体实现中,我希望能够做到:

public IQueryable<T> filter<T>() {
  if (...) return query.OfType<Foo>().Take(100);
  if (...) return query.OfType<Bar>().Blah();
  // etc
}

But of course that doesn't work as the function signature expects T and not Foo or Bar . 但是当然不行,因为函数签名期望T而不是FooBar Is there some simple way to cast this output, or do I need to forgo the generic approach? 是否有一些简单的方法来转换此输出,还是需要放弃通用方法?

Assuming Foo and Bar classes can both be cast as T , something like this would work: 假设FooBar类都可以被强制转换为T ,则可以这样工作:

public IQueryable<T> filter<T>() {
  if (...) return query.OfType<Foo>().Take(100).Cast<T>();
  if (...) return query.OfType<Bar>().Blah().Cast<T>();
  // etc
}

However, you need to make sure that they can both be cast as T , or else you'll obviously get InvalidCastExceptions. 但是,您需要确保可以将它们都强制转换为T ,否则显然您将获得InvalidCastExceptions。 So you would be well-served to make sure T can be cast to either type by changing your declaration to someting along the lines of: 因此,通过按照以下方式将声明更改为someting,可以确保将T强制转换为任何一种类型:

public IQueryable<T> filter<T>() where T : IFooBar

Where IFooBar is the base class/interface for both Foo and Bar 其中IFooBarFooBar的基类/接口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否可以将泛型参数类型限制于此? - Is it possible to constrain a generic parameter type to this? 如何限制泛型方法的嵌套泛型类型 - How to constrain nested generic types of a generic method 是否可以通过方法的名称来约束类型? - Is it possible to constrain a type by the name of a method? 是否可以仅限制记录的方法? - Is it possible to constrain a method for records only? 是否可以将C#泛型方法类型参数约束为“可从”包含类的类型参数“赋值”? - Is it possible to constrain a C# generic method type parameter as “assignable from” the containing class' type parameter? 是否可以将泛型参数约束为当前对象的子类型? - Is it possible to constrain a generic parameter to be a subtype of the current object? 是否可以将泛型类型参数约束为String OR Array - Is it possible to constrain a generic type parameter to String OR Array 是否可以将泛型类型约束到Interface,new()? - Is it possible to constrain generic types to Interface, new()? 是否有(优雅的)解决方案在方法中进一步约束泛型类型参数? - Is there an (elegant) solution to constrain a generic type argument further within a method? 将方法类型参数约束为类通用类型的基础 - Constrain method type argument to be base of class generic type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM