Creating System.Func without specifying a general argument

I have the following code snippet that I use in my tests, which has a bit of duplication:

Func<string, User> getUser = GetFirstItem<User>;

Func<string, Plan> getPlan = GetFirstItem<Plan>;

_planLeader = UserRoleHelper.GetUserWithAdditionalPlans(_commonDao, getUser, getPlan, 5);

The GetFirstItem method has the following signature:

 T GetFirstItem<T>(string whereClause) where T : class

My problem is that I need to create two separate variables getUser and GetPlan for two different function calls in order to explicitly declare a common argument.

Is it possible to create System.Func without declaring a generic type?

Sort of:

Func<T, User> getUser = GetFirstItem<T>;

This obviously will not compile since T is undefined.

Is there any way around this?

+3
source share
2 answers

It would be advisable to do this:

_planLeader = UserRoleHelper.GetUserWithAdditionalPlans(
    _commonDao,
    GetFirstItem<User>,
    GetFirstItem<Plan>,
    5);
+1
source

Why not just use the twice-common method?

Func<string, User> userDelegate = GetFirstItem<string, User>("Hello World");
Func<int, User> userDelegate2 = GetFirstItem<int, User>("Hello World2");

Where your general method looks like this:

public Func<T, U> GetFirstItem<T, U>(string whereClause)
     where T: class
     where U: class
{
   // Logic
}

, , , .

0

Source: https://habr.com/ru/post/1743822/


All Articles