简体   繁体   中英

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.

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM