在C#中,您可以创建类的实例并同时设置变量的值:
public class Object
{
public virtual long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Version { get; set; }
public long ParentId { get; set; }
}
public class Start
{
Object object= new Object()
{
Id = 1,
Name = name,
ParentId = parentId,
Description = null,
Version= 2
};
}
这在Java中是否可行以及如何实现?
答案 0 :(得分:2)
创建实例时设置值的标准方法是只有一个构造函数:
class ExampleObject {
long id;
String name;
String description;
int version;
long parentId;
public ExampleObject(final long id, final String name, final String description, final int version, final long parentId) {
this.id = id;
this.name = name;
this.description = description;
this.version = version;
this.parentId = parentId;
}
}
然后称之为:
ExampleObject exampleObject = new ExampleObject(1, name, null, 2, parentId);
可以使用与您所显示的语法类似的语法,但在使用之前您应该研究一些不足的缺点(并且您也不能使用变量):
ExampleObject exampleObject = new ExampleObject() {{
id = 1;
name = "";
parentId = 2;
description = null;
version = 2;
}};
class ExampleObject {
long id;
String name;
String description;
int version;
long parentId;
}
这样做会创建一个带有静态初始化块的匿名类。静态初始化块看起来像:
class ExampleObject {
long id;
String name;
String description;
int version;
long parentId;
{
id = 1;
name = "";
parentId = 2;
description = null;
version = 2;
}
}
答案 1 :(得分:1)
您可以创建一个接受所有字段值的构造函数。这样,您可以创建该对象的新实例并同时设置所需的值:
public class MyClass {
public long id;
public String name;
public String description;
public int version;
public long parentId;
/** Constructor **/
public MyClass(long id, String name, String description, int version, long parentId) {
this.id = id;
this.name = name;
this.description = description;
this.version = version;
this.parentId = parentId;
}
}
public static void main(String args[]) {
MyClass myClass = new MyClass(1, "name", "description", 1, 1);
}
顺便说一下,不建议(虽然你可以)在Java中命名一个类Object
,因为Java也有一个具有相同名称的类,并且 all Java类从它扩展(可能导致混淆)。
答案 2 :(得分:0)
public class Object
{
public long id;
public String name;
public String description;
public int version;
public long parentId;
public Object(long Id,string Name,string Description,int Version,long Parent_Id)
{
this.Id =Id ;
this.Name =Name ;
this.Description =Description ;
this.Version =Version ;
}