C# 到 Java 的转换
我在转换时遇到问题,尤其是 getter 和 setter。
public class CartItem : IEquatable<CartItem>
{
#region Attributes
public int Quantity { get; set; }
private int _productId;
public int ProductId
{
get { return _productId; }
set
{
_product = null;
_productId = value;
}
}
private Product _product = null;
public Product Prod
{
get
{
if (_product == null)
{
_product = new Product(ProductId);
}
return _product;
}
}
public string Name
{
get { return Prod.ProductName; }
}
public string Description
{
get { return Prod.Description; }
}
public float UnitPrice
{
get { return Prod.UnitPrice; }
}
public float TotalPrice
{
get { return UnitPrice * Quantity; }
}
#endregion
#region Methods
public CartItem(int productId)
{
this.ProductId = productId;
}
public bool Equals(CartItem item)
{
return item.ProductId == this.ProductId;
}
#endregion
}
I'm having trouble converting especially the getter and setter.
public class CartItem : IEquatable<CartItem>
{
#region Attributes
public int Quantity { get; set; }
private int _productId;
public int ProductId
{
get { return _productId; }
set
{
_product = null;
_productId = value;
}
}
private Product _product = null;
public Product Prod
{
get
{
if (_product == null)
{
_product = new Product(ProductId);
}
return _product;
}
}
public string Name
{
get { return Prod.ProductName; }
}
public string Description
{
get { return Prod.Description; }
}
public float UnitPrice
{
get { return Prod.UnitPrice; }
}
public float TotalPrice
{
get { return UnitPrice * Quantity; }
}
#endregion
#region Methods
public CartItem(int productId)
{
this.ProductId = productId;
}
public bool Equals(CartItem item)
{
return item.ProductId == this.ProductId;
}
#endregion
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java 中 getter 和 setter 的示例:
使用您的代码:
以及更多内容:
sample of getters and setters in Java:
using your code:
and something more:
Java 的 getter 和 setter 不像 C# 那样容易使用。在 Java 中,每个 getter 和 setter 都必须显式定义,而不是使用那里的简写。
例如,对于代码“public int ProductId”,您需要一行定义变量,此外还需要两个方法(getter 和 setter),如下所示:
您需要为每个变量定义类似的变量声明和 getter/setter 方法你有变量。
Java getters and setters aren't as easy to use as C#'s. In Java, every getter and setter has to be explicitly defined, rather than using the shorthand you have there.
For example, for your code "public int ProductId", you would need a line defining the variable, in addition two methods (a getter and setter) as follows:
You'd need to define similar variable declarations and getter/setter methods for each variable you have.