所以我有这段代码,灵感来自 javascript 的自初始化匿名函数。
public static Contact Login(string username, string passwordHash = null)
{
return ((Func<Contact, Contact>)(c => {
if (c != null) {
var context = new CurrentContext();
context.Contact = c;
context.Save();
}
return c;
}))(GetContactFromDatabase(username) ?? GetContactFromWebService(username, passwordHash));
}
它工作得很好,但 Func Contact, Contact 对我来说有点冗长。 我希望编译器根据最后传入的参数类型计算出转换。
像这样:
public class AF<T>
{
public static implicit operator T(Func<T, T> fun)
{
return fun();
}
}
但是它不会编译。我想到了一个与 c# 元组类相似的类,它用 15 个不同的 T 来定义自己。
最终代码看起来像这样:
public static Contact Login(string username, string passwordHash = null)
{
return ((AF)(c => {
if (c != null) {
var context = new CurrentContext();
context.Contact = c;
context.Save();
}
return c;
}))(GetContactFromDatabase(username) ?? GetContactFromWebService(username, passwordHash));
}
也许有一个聪明的扩展方法可以完成这个语法糖?
我最终在没有命名空间的类中使用了以下内容:
public delegate T F<T>(T value);
public static class GenericExtensions {
[DebuggerStepThrough]
public static T For<T>(this F<T> function, T value) {
return function(value);
}
}
最佳答案
简单一点,避免使用 lambda:
public static Contact Login(string username, string passwordHash = null)
{
Contact c = GetContactFromDatabase(username) ?? GetContactFromWebService(username, passwordHash);
if (c != null) {
var context = new CurrentContext();
context.Contact = c;
context.Save();
}
return c;
}
关于c# - Func<T, T> 到 T 的通用隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22083903/