EF泛型方法重载
我想让通用方法重载成为可能。 由于我需要在不知道其中包含的泛型类型的情况下创建一个 ObjectSet<..>
,所以我会构建如下内容:
public IQueryable<T> MyMethod<T>() where T : class, (IMyFirst || IMySecond) //notice the syntax..!
{
if(typeOf(T) is IMyFirst..
else ...
}
我怎样才能达到我的目的..?
更新:
@BrokenGlass 写道:
这种类型的约束在 C# 中是不可能的 - 但是您可以约束 IFoo 并让 IMyFirst 和 IMySecond 都实现 IFoo。
但该建议不适用,请参阅:
interface1 { property1 {..}}
interface2 { property2 {..}}
interfaceIFoo : interface1, interface2 { }
通过任何方法:
MyWrapper.Retrieve<EntityProduct>(myObjContext); //error-> EntityProduct implements interface1 only!!
通过其他任何方法:
MyWrapper.Retrieve<EntityOrder>(myObjContext); //error-> EntityOrder implements interface2 only!!
以及此处:
public static IQueryable<T> Retrieve<T>(ObjectContext context) where T :class, interfaceIFoo
{
var query = context.CreateObjectSet<T>().AsQueryable();
//...
I'd like make possible a generic method overload.
Since I need to create an ObjectSet<..>
without knowing the generic type contained in, I wold build something like this:
public IQueryable<T> MyMethod<T>() where T : class, (IMyFirst || IMySecond) //notice the syntax..!
{
if(typeOf(T) is IMyFirst..
else ...
}
How can I reach my purpose..?
Update:
@BrokenGlass wrote:
This type of constraint is not possible in C# - you could however constrain to IFoo and have IMyFirst and IMySecond both implement IFoo.
But that suggestion is not applicable, please see this:
interface1 { property1 {..}}
interface2 { property2 {..}}
interfaceIFoo : interface1, interface2 { }
by any method:
MyWrapper.Retrieve<EntityProduct>(myObjContext); //error-> EntityProduct implements interface1 only!!
by other any method:
MyWrapper.Retrieve<EntityOrder>(myObjContext); //error-> EntityOrder implements interface2 only!!
and here:
public static IQueryable<T> Retrieve<T>(ObjectContext context) where T :class, interfaceIFoo
{
var query = context.CreateObjectSet<T>().AsQueryable();
//...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这种类型的约束在 C# 中是不可能的 - 但是您可以约束到
IFoo
并让IMyFirst
和IMySecond
都实现IFoo
代码>.如果您可以忍受对实体框架的依赖,您也可以使用
EntityObject
This type of constraint is not possible in C# - you could however constrain to
IFoo
and haveIMyFirst
andIMySecond
both implementIFoo
.If you can live with dependencies on Entity Framework you could alternatively also use
EntityObject
析取通用约束实际上没有意义。这些约束为方法提供了编译时信息,因此在编译时导致类型不明确的约束没有多大意义。例如,如果您的方法只是要诉诸运行时类型检查,您不妨这样做:
如果您觉得需要对输入进行类型检查和伪抽象,也许扩展方法恰好相同命名就足够了:
A disjunctive generic constraint doesn't really make sense. Those constraints provide compile-time information to the method, so there's not much point in constraints that result in an ambiguous type at compile time. For instance, if your method is just going to resort to run-time type checking, you might as well just do this:
If you feel you need the type checking on input and a pseudo-abstraction, perhaps extension methods that happen to be identically named would suffice: