我正在将一些经典的 VB6 代码移植到 C# 中,但偶然发现了该PV
函数的用法。
我感觉不对,包括对 Microsoft.VisualBasic 程序集的引用。这是通常做的事情,还是我应该探索更多的选择。我想到的下一个想法是在 Reflector 中探索这个 PV 功能。
我正在将一些经典的 VB6 代码移植到 C# 中,但偶然发现了该PV
函数的用法。
我感觉不对,包括对 Microsoft.VisualBasic 程序集的引用。这是通常做的事情,还是我应该探索更多的选择。我想到的下一个想法是在 Reflector 中探索这个 PV 功能。
C# 和 VB.NET 中Microsoft.VisualBasic的使用已在此问题下进行了彻底讨论。完全支持Microsoft.VisualBasic 命名空间,只要 .Net 存在,它就会存在。没有理由避免它。
编辑:这说明在打字时,这个问题的其他答案是函数的不正确重新实现,以及来自 Code Galleries 的单人乐队不受支持的库。来吧伙计们,微软要从 VB 中删除财务功能将是一件真正的大事。
Microsoft.VisualBasic.Compatibility则完全不同,它专门供 VB6 升级向导使用,现在EDIT 在 .Net 4 中已被标记为已过时(我的预测成真),不应用于新开发。删除对此的引用会有一些优势,但我个人可能会尝试首先引用.Net 3.5 实现一个完全工作的端口。
在 C# 中复制非常简单
public static double PV(double Rate, int nPer, double Pmt, double FV, bool Type)
{
double ann = Math.Pow(1 + Rate, nPer);
return -(FV + Pmt * (1 + (Type ? Rate : 0)) * ((ann - 1) / Rate)) / ann;
}
只是微软提供的公式的重新排列。
我尝试使用接受的答案,但我无法让它在 .NET Core 中工作。我环顾四周,在 github 上遇到了这段代码,这似乎是 Microsoft 的 PV 实现:
Public Function PV(ByVal Rate As Double, ByVal NPer As Double, ByVal Pmt As Double, Optional ByVal FV As Double = 0, Optional ByVal Due As DueDate = DueDate.EndOfPeriod) As Double
Dim dTemp As Double
Dim dTemp2 As Double
Dim dTemp3 As Double
If Rate = 0.0# Then
Return (-FV - Pmt * NPer)
Else
If Due <> 0 Then
dTemp = 1.0# + Rate
Else
dTemp = 1.0#
End If
dTemp3 = 1.0# + Rate
' WARSI Using the exponent operator for pow(..) in C code of PV. Still got
' to make sure that they (pow and ^) are same for all conditions
dTemp2 = dTemp3 ^ NPer
'Do divides before multiplies to avoid OverFlowExceptions
Return (-(FV + Pmt * dTemp * ((dTemp2 - 1.0#) / Rate)) / dTemp2)
End If
End Function
您仍然需要将其转换为 C#。如果我在本文末尾有一个足够通用的实现,我也会发布。