c# - Func<T, T> 到 T 的通用隐式转换

标签 c# generics

所以我有这段代码,灵感来自 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/

相关文章:

swift - 通用工厂方法和类型推断

c# - 为什么访问 com 端口被拒绝?

c# - 通过自定义 msi 安装程序修改 app.config

c# - 将 C++ 结构转换为 C#

.net - IQueryable IGrouping如何工作

typescript - 如何使用基于泛型类型的条件类型来描述约束?

c# - 如何创建返回 bool 值的 Lambda 表达式的 C# 反射

c# - Winforms 中的 HTMLEncode

c# - 从字符串创建类实例和调用方法

c# - 在泛型类 <T,U> 的方法中比较 T 的两个变量(从 C++ 到 C# 的代码移植)