问题描述
在C#中使用 var 关键字是隐式类型声明。 var 的Java等效语法是什么?
One use of the var keyword in C# is implicit type declaration. What is the Java equivalent syntax for var?
推荐答案
没有。唉,你必须输入完整的类型名称。
There is none. Alas, you have to type out the full type name.
编辑:发布后7年,输入局部变量的推断(带 var 。
7 years after being posted, type inference for local variables (with var
) was added in Java 10.
编辑:发布后6年,从下面收集一些评论:
6 years after being posted, to collect some of the comments from below:
-
C#具有
var
关键字的原因是因为可能有类型没有.NET中的名称。例如:
The reason C# has the
var
keyword is because it's possible to have Types that have no name in .NET. Eg:
var myData = new { a = 1, b = "2" };
在这种情况下,无法为 myData提供正确的类型
。 6年前,这在Java中是不可能的(所有类型都有名字,即使它们非常冗长和不适合)。我不知道这是否在平均时间内发生了变化。
In this case, it would be impossible to give a proper type to myData
. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.
var
与以下内容不同动态
。 var
iables仍然是100%静态类型。这不会编译:
var
is not the same as dynamic
. var
iables are still 100% statically typed. This will not compile:
var myString = "foo";
myString = 3;
var
在以下情况下也很有用从上下文来看,这种类型很明显例如:
var
is also useful when the type is obvious from context. For example:
var currentUser = User.GetCurrent();
我可以说在我负责的任何代码中, currentUser
中包含用户
或派生类。显然,如果你的 User.GetCurrent
的实现返回一个int,那么这可能对你不利。
I can say that in any code that I am responsible for, currentUser
has a User
or derived class in it. Obviously, if your implementation of User.GetCurrent
return an int, then maybe this is a detriment to you.
这与 var
无关,但如果你有奇怪的继承层次结构,你可以用其他方法隐藏方法(例如 new public void DoAThing ()
),不要忘记非虚拟方法会受到类型转换的影响。
This has nothing to do with var
, but if you have weird inheritance hierarchies where you shadow methods with other methods (eg new public void DoAThing()
), don't forget that non-virtual methods are affected by the Type they are cast as.
我无法想象一个现实世界的场景,这表明设计很好,但这可能无法按预期工作:
I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:
class Foo {
public void Non() {}
public virtual void Virt() {}
}
class Bar : Foo {
public new void Non() {}
public override void Virt() {}
}
class Baz {
public static Foo GetFoo() {
return new Bar();
}
}
var foo = Baz.GetFoo();
foo.Non(); // <- Foo.Non, not Bar.Non
foo.Virt(); // <- Bar.Virt
var bar = (Bar)foo;
bar.Non(); // <- Bar.Non, not Foo.Non
bar.Virt(); // <- Still Bar.Virt
如上所示,虚拟方法不受此影响。
As indicated, virtual methods are not affected by this.
不,在没有实际变量的情况下初始化 var
没有非笨拙的方法。
No, there is no non-clumsy way to initialize a var
without an actual variable.
var foo1 = "bar"; //good
var foo2; //bad, what type?
var foo3 = null; //bad, null doesn't have a type
var foo4 = default(var); //what?
var foo5 = (object)null; //legal, but go home, you're drunk
在这种情况下,就这样做吧老式的方式:
In this case, just do it the old fashioned way:
object foo6;
这篇关于Java中C#'var'关键字的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!