小编Fan*_*Fan的帖子

泛型类型参数的多个约束的优先级

在下面的示例中,我有两个约束,Foobar并且IFoobar<T>在泛型类中的类型T上FoobarList<T>.但是编译器给出了一个错误:无法将类型'Foobar'隐式转换为'T'.存在显式转换(您是否错过了演员?)

interface IFoobar<T>
{
    T CreateFoobar();
}

class Foobar : IFoobar<Foobar>
{
    //some foobar stuffs
    public Foobar CreateFoobar() { return new Foobar(); }
}

class FoobarList<T> where T : Foobar, IFoobar<T>
{
    void Test(T rFoobar)
    {
        T foobar = rFoobar.CreateFoobar(); //error: cannot convert Foobar to T
    }
}
Run Code Online (Sandbox Code Playgroud)

看起来编译器认为CreateFoobar是Foobar中的一种方法,但不是IFoobar中的方法.我可以通过将Foobar划分为基类FoobarBase并在其派生类中实现接口IFoobar来修复编译,如下所示:

interface IFoobar<T>
{
    T CreateFoobar();
}

abstract class FoobarBase
{
    //some foobar stuffs
}

class Foobar : FoobarBase, IFoobar<Foobar>
{
    public Foobar CreateFoobar() { return …
Run Code Online (Sandbox Code Playgroud)

c# generics type-constraints

6
推荐指数
1
解决办法
133
查看次数

一个 static_assert 使另一个 static_assert 失败(内部类的 is_default_constructible)

以下代码编译:

struct Bar
{
    struct Foo
    {
        int v = 0;
    };

    // If uncomment the following line, both static assert will fail
    // static_assert(std::is_default_constructible_v<Foo>);
};

static_assert(std::is_default_constructible_v<Bar::Foo>);
Run Code Online (Sandbox Code Playgroud)

但是如果我取消注释 first static_assert,两者static_assert都会失败。这怎么会发生?

请参阅http://coliru.stacked-crooked.com/a/64e9c020056e37ed 中的代码

c++ static-assert inner-classes default-constructor type-traits

5
推荐指数
0
解决办法
38
查看次数

从并行流中收集结果

我有一段这样的代码:

List<Egg> eggs = hens.parallelStream().map(hen -> {
    ArrayList<Egg> eggs = new ArrayList<>();
    while (hen.hasEgg()) {
        eggs.add(hen.getEgg());
    }
    return eggs;
}).flatMap(Collection::stream).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但是通过这种方式,我必须为每只母鸡创建一个ArrayList,并且在母鸡100%处理之前不会收集鸡蛋.我想要这样的东西:

List<Egg> eggs = hens.parallelStream().map(hen -> {
    while (hen.hasEgg()) {
        yield return hen.getEgg();
    }
}).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但Java没有收益率.有没有办法实现它?

java parallel-processing java-8 java-stream

3
推荐指数
1
解决办法
2264
查看次数

Linq造成的性能损失

最近的更新导致我的代码中出现严重的性能损失.通过使用剖析器,我发现损失是由使用Linq的一条线引起的.我做了一些测试,发现Linq慢得多foreach.

        List<int> numbers = new List<int>();
        for (int i = 0; i < 1000; ++i)
            numbers.Add(i);
        var stopWatch = new Stopwatch();

        {
            int total = 0;
            for (int i = 0; i < 1000; ++i)
                total += i;
        }
        stopWatch.Start();
        for (int j = 0; j < 1000000; ++j)
        {
            int total = 0;
            for (int i = 0; i < 1000; ++i)
                total += i;
        }
        stopWatch.Stop();
        Console.WriteLine("Benchmark run time: {0}", stopWatch.ElapsedMilliseconds);

        {
            int total = 0; …
Run Code Online (Sandbox Code Playgroud)

c# linq performance foreach

-7
推荐指数
2
解决办法
177
查看次数