繁体   English   中英

自定义可为空<t>扩展方法和 SelectMany</t>

[英]Custom Nullable<T> Extension Methods and SelectMany

Nullable<T>有如下扩展方法。

using System;
using System.Runtime.CompilerServices;

namespace DoNotationish
{
    public static class NullableExtensions
    {
        public static U? Select<T, U>(this T? nullableValue, Func<T, U> f)
            where T : struct
            where U : struct
        {
            if (!nullableValue.HasValue) return null;
            return f(nullableValue.Value);
        }

        public static V? SelectMany<T, U, V>(this T? nullableValue, Func<T, U?> bind, Func<T, U, V> f)
            where T : struct
            where U : struct
            where V : struct
        {
            if (!nullableValue.HasValue) return null;
            T value = nullableValue.Value;
            U? bindValue = bind(value);
            if (!bindValue.HasValue) return null;
            return f(value, bindValue.Value);
        }
    }
}

这允许在查询语法中使用Nullable<T> 以下测试将通过。

        [Test]
        public void Test1()
        {
            int? nv1 = 5;
            int? nv2 = 3;
            var q = from v1 in nv1
                    from v2 in nv2
                    select v1 + v2;
            Assert.AreEqual(8, q);
        }

        [Test]
        public void Test2()
        {
            int? nv1 = null;
            int? nv2 = 3;
            var q = from v1 in nv1
                    from v2 in nv2
                    select v1 + v2;
            Assert.IsNull(q);
        }

但是,如果您尝试链接 3 个或更多,它将被视为匿名类型并且不会编译。

        [Test]
        public void Test3()
        {
            int? nv1 = 5;
            int? nv2 = 3;
            int? nv3 = 8;
            var q = from v1 in nv1
                    from v2 in nv2  // Error CS0453: anonymous type is not struct
                    from v3 in nv3
                    select v1 + v2 + v3;
            Assert.AreEqual(16, q);
        }

您可以通过如下所示手动指定使用ValueTuple来解决此问题,但这很难看。

        [Test]
        public void Test3_()
        {
            int? nv1 = 5;
            int? nv2 = 3;
            int? nv3 = 8;
            var q = from v1 in nv1
                    from v2 in nv2
                    select (v1, v2) into temp      // ugly
                    from v3 in nv3
                    select temp.v1 + temp.v2 + v3; // ugly
            Assert.AreEqual(16, q);
        }

这些简化的例子可以简单地通过使用+运算符来解决: var q = nv1 + nv2 + nv3;

但是,如果您能流畅地编写用户定义的结构,您会发现使用它会更方便。 有什么好办法吗?

想想编译器如何将查询表达式转换为SelectMany调用。 它会把它变成这样的东西:

var q =
    nv1.SelectMany(x => 
       nv2.SelectMany(x => nv3, (v2, v3) => new { v2, v3 }), 
       (v1, v2v3) => v1 + v2v3.v2 + v2v3.v3);

注意第二个SelectMany调用的V是如何被推断为匿名 class 的,这是一个引用类型,不符合: struct的约束。

请注意,它专门使用匿名 class,而不是ValueTuple ( (v2, v3) => (v2, v3) )。 这是在语言规范中指定的:

带有第二个 from 子句的查询表达式,后跟 select 子句以外的内容:

 from x1 in e1 from x2 in e2...

被翻译成

from * in ( e1 ). SelectMany( x1 => e2, ( x1, x2 ) => new { x1, x2 } )...

所以不幸的是,你对此无能为力。 您可以尝试分叉Roslyn编译器,使其编译为创建一个ValueTuple ,但从技术上讲,这不再是“C#”了。

OTOH,如果您编写自己的Nullable<T>类型并且不将T限制为值类型,这个想法可能会奏效,但我不确定这是否值得。

我们来看看这个查询

from a in source1
from b in source2
from c in source3
from d in source4
// etc
select selector // how is it possible that a, b, c, d available in selector?

此类查询将编译为 SelectMany 调用链

SelectMany(IEnumerable<TSource> source, 
           Func<TSource, IEnumerable<TCollection>> collectionSelector,
           Func<TSource, TCollection, TResult> resultSelector)

如您所见,它在结果选择器中只能接受两个 arguments - 一个是源集合类型,另一个是选择器返回的第二个集合类型。 因此,将两个以上的 arguments 向下传递到链中(以便所有 arguments 最终将到达最后一个结果选择器)的唯一方法是创建匿名类型。 这就是它的样子:

source1
  .SelectMany(a => source2, (a, b) => new { a, b })
  .SelectMany(x1 => source3, (x1, c) => new { x1, c })
  .SelectMany(x2 => source4, (x2, d) => selector(x2.x1.a, x2.x1.b, x2.c, d));

同样,结果选择器限制了两个输入 arguments。因此,对于您传递的 Test1 和 Test2,不会创建匿名类型,因为两个 arguments 都可以传递给结果选择器。 但是 Test3 需要三个 arguments 作为结果选择器,并为此创建了一个中间匿名类型。


您不能使您的扩展方法同时接受可为空的结构和生成的匿名类型(它们是引用类型)。 我建议您创建特定于域的扩展方法BindMap 这些方法中的一对将与函数式编程领域保持一致,而不是from v1 in nv1

public static U? Bind<T, U>(this T? maybeValue, Func<T, U?> binder)
    where T : struct
    where U : struct
        => maybeValue.HasValue ? binder(maybeValue.Value) : (U?)null;

public static U? Map<T, U>(this T? maybeValue, Func<T, U> mapper)
    where T : struct
    where U : struct
        => maybeValue.HasValue ? mapper(maybeValue.Value) : (U?)null;

和用法

nv1.Bind(v1 => nv2.Bind(v2 => nv3.Map(v3 => v1 + v2 + v3)))
   .Map(x => x * 2) // eg

Nullable<T>有如下扩展方法。

using System;
using System.Runtime.CompilerServices;

namespace DoNotationish
{
    public static class NullableExtensions
    {
        public static U? Select<T, U>(this T? nullableValue, Func<T, U> f)
            where T : struct
            where U : struct
        {
            if (!nullableValue.HasValue) return null;
            return f(nullableValue.Value);
        }

        public static V? SelectMany<T, U, V>(this T? nullableValue, Func<T, U?> bind, Func<T, U, V> f)
            where T : struct
            where U : struct
            where V : struct
        {
            if (!nullableValue.HasValue) return null;
            T value = nullableValue.Value;
            U? bindValue = bind(value);
            if (!bindValue.HasValue) return null;
            return f(value, bindValue.Value);
        }
    }
}

这允许Nullable<T>在查询语法中使用。 以下测试将通过。

        [Test]
        public void Test1()
        {
            int? nv1 = 5;
            int? nv2 = 3;
            var q = from v1 in nv1
                    from v2 in nv2
                    select v1 + v2;
            Assert.AreEqual(8, q);
        }

        [Test]
        public void Test2()
        {
            int? nv1 = null;
            int? nv2 = 3;
            var q = from v1 in nv1
                    from v2 in nv2
                    select v1 + v2;
            Assert.IsNull(q);
        }

但是,如果您尝试链接 3 个或更多,它将被视为匿名类型并且不会编译。

        [Test]
        public void Test3()
        {
            int? nv1 = 5;
            int? nv2 = 3;
            int? nv3 = 8;
            var q = from v1 in nv1
                    from v2 in nv2  // Error CS0453: anonymous type is not struct
                    from v3 in nv3
                    select v1 + v2 + v3;
            Assert.AreEqual(16, q);
        }

您可以通过手动指定使用ValueTuple来解决此问题,如下所示,但这很难看。

        [Test]
        public void Test3_()
        {
            int? nv1 = 5;
            int? nv2 = 3;
            int? nv3 = 8;
            var q = from v1 in nv1
                    from v2 in nv2
                    select (v1, v2) into temp      // ugly
                    from v3 in nv3
                    select temp.v1 + temp.v2 + v3; // ugly
            Assert.AreEqual(16, q);
        }

这些简化的例子可以通过使用+运算符简单地解决: var q = nv1 + nv2 + nv3;

但是,如果您能流利地编写它,您会发现使用用户定义的结构会更方便。 有什么好办法吗?

暂无
暂无

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

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