开发者

Java: Converting from .NET Constructors

开发者 https://www.devze.com 2023-01-11 00:19 出处:网络
We\'re converting some .NET 3.5 code to Java (Android). This Java code gives the error: Syntax error on token \"Chapters\", VariableDeclaratorId expected after this token

We're converting some .NET 3.5 code to Java (Android).

This Java code gives the error:

Syntax error on token "Chapters", VariableDeclaratorId expected after this token

this.add (new Book() {Chapters=50, OneBasedBookID = 1, 
Long = "Bahai", Short = "ba", Color = c,   BookType = b; 开发者_运维知识库});

The types are all correct.


You are using .NET/C#'s ability to initialize properties at the time you create your object. To do it in Java (or in older C#), you are going to have to do it the long way.

Book book = new Book();
book.Chapters = 50;
// etc
this.add(book);


Java doesn't have object initializers, so this syntax is not valid.

Instead, you're probably looking to do something like this:

Book book = new Book();

book.Chapters = 50;
book.OneBasedBookID = 1;
book.Long = "Bahai";
book.Short = "ba";
book.Color = c;
book.BookType = b;

this.add(book);

Also note that Java has no concept of "proper" properties either, and typical "good" practice is to use getters/setters, and to not name your variables starting with upper-case letters. This wouldn't work for your Long and Short members though, and overall these practices may not provide any value in your scenario anyway.


You could use the anonymous class initializer trick:

this.add (new Book() {{
    Chapters=50;
    OneBasedBookID = 1;
    Long = "Bahai";
    Short = "ba";
    Color = c;
    BookType = b;
}});
0

精彩评论

暂无评论...
验证码 换一张
取 消