Java的“属性”是否与C#中的属性相同?
在C#中,您可以使用属性使数据字段可公开访问(允许用户直接访问它),同时保留在这些直接访问的字段上执行数据validation的function。 Java有类似的东西吗? 对于Instance,假设存在一个带有以下实现的C#类(见下文):
public class newInt{ public newInt(){...} public int x{ get{ return this.x } set{ this.x = isValid(value) } } } private static int isValid(int value){...}
类中的这个定义允许用户在从中检索值并为其赋值时“自然地”使用数据字段“x”。 以下是它将如何在主要使用。
public class Test{ public static void main(String[] args){ newInt a = new newInt(); ax = 50; int b = ax; } }
问题是…… java也可以这样做吗? 如果是这样,它叫什么?
没有。
这就是Java拥有getter / setter的原因。
在C#中,您通常会遇到以下情况:
public class SomeObject { private string _title = ""; public string Title { get { return _title; } set { _title = value; } } } // Or with Auto-Properties public class SomeObjectAutoProperties { public string Title { get; set; } }
Java getter / setter等价物将是:
public class SomeObject { private String _title = ""; public string getTitle() { return _title; } public void setTitle(String value) { _title = value; } }
有Java平台,还有Java语言。
Java语言不支持属性(可能永远不会),但您不必使用Java语言来使用Java平台(就像您不需要坚持使用C#来使用.NET平台一样) )。
校验:
还有很多其他人。
不,你会使用getter和setter方法。 这是一个Java惯例。
public class newInt { public newInt() {...} private int _x = 0; public int getX() { return this._x; } public void setX(int x) { this._x = isValid(x); } }
不,Java没有属性。 Java习语是使用mutator / accessor(getter / setter)。 尽管很多人都赞成添加它们,但它们不太可能包含在下一个版本中(Java 7)。
奇怪的是,JavaFX具有属性。
请记住,当Java诞生时,它从C ++中借鉴了很多想法。 因此,一些语法和习语与该语言非常相似。
不,它没有。
我真的有一个问题需要理解这个C#属性,因为,我认为其中一条规则是尽可能少地执行代码,因为它们已经公开,为什么不使用公共属性呢?
所以,你的Java等价物(可能很难看)将是:
public class NewInt { // In Java class names start with uppercase by convention public int x; }
你使用它像:
NewInt ni = new NewInt(); ni.x = 50; int b = ni.x;
我肯定会有一些东西是肯定的,但是,大多数情况下这都会这样做(顺便说一句,我从来没有这样编码:P)
BTW
我不太喜欢getter和setter,但我接受它们作为Java约定的一部分。
我只是希望他们用这个代替:
public class NewInt { private int x; public int x(){ return this.x; } public void x(int value ) { this.x=value; } }
因此用法将是:
NewInt a = new NewInt(); ax(10); int b = ax();
可能在下一个Java生活中。
- 针对多个Web请求的最佳multithreading方法
- 在C#中查找有关通过USB连接的所有串行设备的信息
- 如何禁用WPF MenuItem中的助记符?
- 将.json文件加载到c#程序中
- entity framework代码第一个关联/ FK问题和假设/默认值
- 我可以在.net中没有.config文件的情况下指定supportedRuntime(或任何其他配置参数)吗?
- 为什么我收到错误“类型’IReturn ‘是在未引用的程序集中定义的”使用VIsualStudio 2017中的ServiceStack
- 如何在LINQ中询问“是否只有一个满足条件的元素”?
- 我可以将这块XAML变成可重复使用的“控件”吗?