[英]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.