简体   繁体   English

格式 function - VB6 到 C# 转换

[英]Format function - VB6 to C# conversion

What is the C# equivalent of: C# 相当于:

Public stringValue As String
Public intValue As Integer

intValue = Format(val(stringValue), "00")

? ?

So the vb6 Format function converts to string and the Val function converts to a number.因此 vb6 Format function 转换为字符串,而Val function 转换为数字。 If you look at the Microsoft documentation for Val :如果您查看Val 的 Microsoft 文档

Val("    1615 198th Street N.E.")
// returns
1615198

in c# this can clumsily be converted to在 c# 这可以笨拙地转换为

string stringValue = "    1615 198th Street N.E.";

// assign to int if int wanted
// throws exception if cannot be converted to int, use Int32.TryParse if you want to handle that
int intValue = System.Convert.ToInt32(
    new string(stringValue.Replace(" ", "").TakeWhile(System.Char.IsDigit).ToArray())
);

System.Console.WriteLine(intValue);

it's really going to depend on what your expectations are for what stringValue is going to be and what you want returned.这实际上取决于您对stringValue将是什么以及您希望返回什么的期望。 Also I don't think you can assign a string value to an int so willy nilly like you can in vb6.另外,我认为您不能像在 vb6 中那样随意将string值分配给int It can definitely be cleaned up but that just depends on what you're doing.它绝对可以清理,但这取决于你在做什么。

edit: Since you're testing a stringValue = "3" this should work编辑:由于您正在测试stringValue = "3"这应该可以

string stringVal = "3";
if(!System.Int32.TryParse(stringVal, out int intValue))
{
    System.Console.WriteLine($"value={stringVal} not of type int");
}
return intValue;

If truly replicating the VB6 Val function is desired, then Microsoft.VisualBasic.Val can be used.如果需要真正复制 VB6 Val function,则可以使用Microsoft.VisualBasic.Val It is pretty faithful to the original, and of course can be called from C#.它非常忠实于原作,当然可以从 C# 调用。

See https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.conversion.val?view=netcore-3.1#Microsoft_VisualBasic_Conversion_Val_System_String_ for the string overload (returns Double).有关字符串重载(返回 Double),请参阅https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.conversion.val?view=netcore-3.1#Microsoft_VisualBasic_Conversion_Val_System_String_

One aspect where it doesn't return the same result as VB6 is for a string like "3.4.5".它不返回与 VB6 相同的结果的一个方面是像“3.4.5”这样的字符串。 VB6 Val will return 34.5, while the.Net Val will return 3.4. VB6 Val将返回 34.5,而 .Net Val将返回 3.4。

No need for exception handling (just like with VB6), if the input can't be converted to a number, no exception is thrown (well, mostly, there are some edge cases) or error returned, the return value is zero.不需要异常处理(就像 VB6 一样),如果输入不能转换为数字,则不会抛出异常(嗯,大多数情况下,有一些边缘情况)或返回错误,返回值为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM