我有一个看起来像这样的课程
public class CacheManger<T> where T : class, new()
{
public CacheManger(Func<int, T> retriveFunc, Func<List<T>> loadFunc)
{
_retriveFunc = retriveFunc;
_loadFunc = loadFunc;
}
public T GetValueByid(int id)
{
return _retriveFunc(id);
}
}
我有另一个课程如下
public class AccountCache
{
public AccountCache ()
{
CacheManager = new CacheManger<Account>(GetAccount, LoadAcc);
// LoadAcc is another method that returns a List<Account>
}
private Account GetAccount(int accID)
{
return CacheManager.CacheStore.FirstOrDefault(o => o.ID == accID);
//CacheStore is the List<T> in the CacheManager.(internal datastore)
}
public Account GetProdServer(int accID)
{
return CacheManager.GetValueByid(accID);
}
}
现在您可以看到我可以将GetAccount
传递给CacheManager
的构造函数。现在我有另一个类,我有这样的方法
public User GetUser(string accountID, int engineID)
{
}
我怎样才能将此函数传递给CacheManager
的构造函数。
我可以携带函数,但是我怎么能把它作为构造函数参数传递?
我现在在做什么:
private User GetUserInternal(string accountID, int engineID)
{
return
/* actual code to get user */
}
private Func<string, Func<int, User>> Curry(Func<string, int, User> function)
{
return x => y => function(x, y);
}
public UserGetAccount(string accountID, int engineID)
{
_retriveFunc = Curry(GetUserInternal)(accountID);
CacheManager.RetrivalFunc = _retriveFunc; //I really dont want to do this. I had to add a public property to CacheManager class for this
return CacheManager.GetValueByid(engineID);// This will call GetUserInternal
}
答案 0 :(得分:1)
你可能想要部分应用而不是currying。我发现的最好方法是创建N个函数,这些函数取自1-N通用参数,然后让编译器选择你想要的那个。如果您查看我的language-ext项目,我有两个函数,一个名为curry
,一个名为par
,用于currying和部分应用:
要部分申请,请执行以下操作:
// Example function
int AddFour(int a,int b,int c, int d)
{
return a + b + c + d;
}
// This returns a Func<int,int,int> with the first two arguments 10 & 5 auto-provided
var tenfive = par(AddFour, 10, 5);
// res = 10 + 5 + 1 + 2
var res = tenfive(1,2);
要咖喱,请这样做:
// Example function
int AddFour(int a,int b,int c, int d)
{
return a + b + c + d;
}
// Returns Func<int,Func<int,Func<int,Func<int,int>>>>
var f = curry(AddFour);
// res = 10 + 5 + 1 + 2
var res = f(10)(5)(1)(2);