什么是Java相当于建立在C#中的匿名对象? [英] What is the Java equivalent of creating an anonymous object in C#?

查看:282
本文介绍了什么是Java相当于建立在C#中的匿名对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,你可以做到以下几点:

In C#, you can do the following:

VAR objResult =新{成功=结果};

有一个java相当于呢?

Is there a java equivalent for this?

推荐答案

Java那样没有由 VAR 关键字提供给C#类型推断,所以虽然你可以创建匿名类型他们不是多好,因为你不能在他们的属性得到的。

Java does not have type inference provided to C# by the var keyword, so whilst you can create anonymous types they're not much good since you can't get at their attributes.

所以,你可以创建一个像这样的匿名类的一个实例:

So you can create an instance of an anonymous class like so:

Object myobj = new Object() {
  public final boolean success = true;
}



不过,由于 MyObj中对象的实例您无法访问成功在你的代码,并且您已经创建的实例的匿名的类

But since myobj is an instance of Object you can't access success in your code, and as you have created an instance of an anonymous class there is by definition no way to explicitly refer to this class.

有是定义没有办法明确地提及这一类,在C# VAR 解决了这一点,但没有办法在Java中做到这一点。

In C# var solves this by inferring the type but there is no way to do this in Java.

通常匿名类用于创建接口实现和抽象类等使用接口或父类作为类型引用。

Normally anonymous classes are used to create implementations of interfaces and abstract classes and so are referenced using the interface or parent class as the type.

这篇关于什么是Java相当于建立在C#中的匿名对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆