繁体   English   中英

MaybeMonad中的类型推断

[英]Type inference in MaybeMonad

我正在尝试从此站点进行示例,但遇到以下推理问题。

该示例可能涉及Monads,并避免了连续的空值检查并以线性方式编写代码。

无法从用法中推断方法Maybe<Customer>.Bind<TO>(Func<Customer, Maybe<TO>>)的类型参数。 尝试显式指定类型参数。

也许.cs

using System;

namespace Monads
{
    public class Maybe<T> where T : class
    {
        private readonly T value;

        public Maybe(T someValue) 
        {
            if(someValue == null) 
                throw new ArgumentNullException(nameof(someValue));
            this.value = someValue;
        }

        private Maybe(){}

        public Maybe<TO> Bind<TO>(Func<T, Maybe<TO>> func) where TO : class
        {
            return value != null ? func(value) : Maybe<TO>.None();
        }

        public static Maybe<T> None() => new Maybe<T>();
    }
}

IMonadic存储库

namespace Monads
{
    public interface IMonadicRepository
    {
       Maybe<Customer> GetCustomer(int id);
       Maybe<Address> GetAddress(int id);
    }
}

仓库.cs

namespace Monads {
    public class Repository : IMonadicRepository
    {
        public Maybe<Customer> GetCustomer(int id) {
            return new Maybe<Customer>(new Customer(id));
        }

        public Maybe<Address> GetAddress(int id)
        {
            return new Maybe<Address>(new Address(id));
        }
    }
}

客户.cs

namespace Monads
{
    public class Customer 
    {
        public Customer(int id) {
        }

        public Address Address {get; set;}
    }
}

地址.cs

namespace Monads 
{
    public class Address 
    {
        public Address(int id) {
        }
    }
}

用法-Programs.cs

namespace Monads
{
    class Program
    {
        static void Main(string[] args)
        {
            IMonadicRepository repository = new Repository();
            repository.GetCustomer(1)
                .Bind(customer => customer.Address); // error
        }
    }
}

错误 :无法从用法中推断方法'Maybe.Bind(Func>)'的类型参数。 尝试显式指定类型参数。

您的问题是在.Bind(customer => customer.Address)行中, customer.Address的类型为Address 但是, Bind函数需要一个lambda来返回Maybe<Address>而不是Address

我不确定这是否是正确的方法,但是一种选择是使用帖子中定义的Return扩展方法:

repository.GetCustomer(1)
    .Bind(c => c.Address.Return());

为了完成,我还将在这里复制它:

public static class MaybeExtensions
{
    public static Maybe<T> Return<T>(this T value) where T : class
    {
        return value != null ? new Maybe<T>(value) : Maybe<T>.None();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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