简体   繁体   English

Java等效C#隐式

[英]Java equivalent c# implicit

I have an object A 我有一个物体A

class A {
    B contained = new B();
}

class B
{
}

and a collection of A's 和A的集合

Queue<A> q1 = new PriorityQueue<A>();  

what I want to do 我想做的事

Queue<B> q2 = new PriorityQueue<B>(q1);

in c# I can use the implicit keyword, is there an equivalent? 在C#中,我可以使用隐式关键字,是否有一个等效的?

No, you need to have 不,你需要

Queue<B> q2 = new PriorityQueue<B>();
for(A a: q1) q2.add(a.contained);

I can't image you would want to do this very often. 我无法想象您会经常这样做。 Is this a very useful feature? 这是一个非常有用的功能吗?

First of all, if you use PriorityQueue in Java, then the classes needs to implement comparable interface. 首先,如果在Java中使用PriorityQueue ,则这些类需要实现可比较的接口。 Next thing to do, is to think what kind of equality contract do you want between A and B . 接下来要做的是考虑您想要在AB之间A什么样的平等契约。 Keyword implicit in C# seems to be a simple cast transform. C#中implicit关键字似乎是一个简单的强制转换。

I imagine equivalent in Java would look like: 我想象Java中的等效形式如下:

    Queue<A> q1 = new PriorityQueue<A>(Arrays.asList(new A(), new A(), new A()));
    Queue<B> q2 = new PriorityQueue<B>(Collections2.transform(q1, A.toB));

Class A would probably look like: A类可能看起来像:

static class A implements Comparable<A> {
    B contained = new B();

    public static final Function<A, B> toB = new Function<A, B>() {
        @Override public B apply(A a) {
            return a.contained;
        }
    };

    @Override public int compareTo(A a) {
        return contained.compareTo(a.contained);
    }
}

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

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