简体   繁体   English

为什么我们不能在非泛型类中使用泛型方法?

[英]Why can't we have generic methods inside non-generic classes?

In C# the following is valid: 在C#中,以下内容有效:

public class X {
    public void F<T>(T t) {}
}

and do: 并做:

var x = new X();
x.F(2);

and that's not possible in Java. 这在Java中是不可能的。

I know generics work different in both languages, but I'm still wondering... 我知道泛型在两种语言中的工作方式都不同,但是我仍然想知道...

Is there a good reason for that? 有充分的理由吗?

The syntax is different: 语法不同:

public class X {
    public <T> void F(T t) {}
}

Just so you know you CAN have generic methods inside non-generic classes in Java. 众所周知,您可以在Java的非泛型类中拥有泛型方法。

It would look like this -- 看起来像这样-

public class Test {

        public <T> void func(T t) {
    // do something.
            }
}

When do you call it, test.func(2) , the 2 gets autoboxed into an Integer object 何时调用test.func(2),将2自动装箱到Integer对象中

EDIT : To answer your question, whatever you are asking is exactly possible in Java. 编辑:要回答您的问题,无论您要问什么,在Java中都是完全可能的。

您可以,只需移动您的通用声明。

public <T> void F(T t){}

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

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