[英]Generic extension method with custom return type
我正在尝试为两个实体编写扩展方法。
首先找到对象的类型,然后与另一个表进行inner join
。
如果它是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; }
}
听起来您根本不应该使用泛型。 泛型适用于您的泛型方法不需要知道类型的情况。 通用类型参数表示此方法可以与任何具体类型一起使用。
也许您应该在这两种情况下都只有两种特殊情况的方法。 这使得所有的转换和复杂性消失了。
但是,如果您坚持使用通用方法,请按以下步骤操作。 首先创建我所说的特殊情况方法。
public static C GetAllInfo(this IQueryable<A> objCust); //implement this
public static C GetAllInfo(this IQueryable<B> objCust); //implement this
然后委托给他们:
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.