[英]Generic extension method with custom return type
I am trying to write an extension method for two entities. 我正在尝试为两个实体编写扩展方法。
First find the type of object, then do an inner join
with another table. 首先找到对象的类型,然后与另一个表进行
inner join
。
If it's type A then Join
must be with B. If it's type B then join with A. But I got stuck on the Join
condition. 如果它是A类型,则
Join
必须与B在一起。如果它是B类型,则必须与A加入。但是我陷入了Join
条件。
public static C GetAllInfo<T>(this IQueryable<T> objCust)
{
if (typeof(T) == typeof(B))
{
//prepare the Object based on the Type
var objCastReg = objCust as IQueryable<B>;
//how to write join here ?????
var objUsermaster=objCastReg.GroupJoin(A,um=>um.UserId,r=>r.)
//Build the Class object from two retrieved objects.
}
if (typeof(T) == typeof(A))
{
var objCast = objCust as IQueryable<A>;
}
return null;
}
public class C
{
public A A{ get; set; }
public B B{ get; set; }
}
Sounds like you shouldn't use generics at all. 听起来您根本不应该使用泛型。 Generics are for when your generic method does not need to know the type.
泛型适用于您的泛型方法不需要知道类型的情况。 A generic type parameter signals that this method can work with any concrete type whatsoever.
通用类型参数表示此方法可以与任何具体类型一起使用。
Maybe you should just have two special-cased method for both cases here. 也许您应该在这两种情况下都只有两种特殊情况的方法。 That makes all the casting and complexity go away.
这使得所有的转换和复杂性消失了。
But if you insist on a generic method, here is how to do it. 但是,如果您坚持使用通用方法,请按以下步骤操作。 First create the special-case method I was speaking of.
首先创建我所说的特殊情况方法。
public static C GetAllInfo(this IQueryable<A> objCust); //implement this
public static C GetAllInfo(this IQueryable<B> objCust); //implement this
Then delegate to them: 然后委托给他们:
public static C GetAllInfo<T>(this IQueryable<T> objCust)
{
if (typeof(T) == typeof(B))
{
return GetAllInfo((IQueryable<B>)objCust); //call to specialized impl.
}
if (typeof(T) == typeof(A))
{
return GetAllInfo((IQueryable<A>)objCust); //call to specialized impl.
}
//fail
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.