问题描述
class Product
{
public float cost{set;get;}
public float sellprice{set;get}
}
public class Myviewmodel
{
public Product products{set;get}
public float profit{set;get}
}
问题是我需要从Product
属性中计算利润,但我不知道该怎么做。
解决方法
使用带有表达式获取器的属性,如下所示:
public class MyViewModel{
public MyViewModel( Product product )
{
this.Product = product ?? throw new ArgumentNullException(nameof(product));
}
public Product Product { get; }
public Decimal Profit => this.Product.SellPrice - this.Product.Cost;
}
其他反馈:
- 在C#和.NET中:
- 提供类型(
class
,struct
,interface
等)PascalCase
名称。 - 提供专用字段,参数和本地
camelCase
名称。 - 提供公共成员(属性,方法)
PascalCase
名称。
- 提供类型(
- 请勿使用
float
或double
来表示货币。- Why not use Double or Float to represent currency?
- 它们是IEEE-754近似值,不能准确表示某些(大多数)十进制值。
- 改为使用
System.Decimal
-或使用int
美分(乘以100x)。
- 您应该致力于使用具有只读属性的不可变类型。
- 可变状态使您更难以推理应用程序中的数据流。