converting a vb.net code snippet to c#
Visual Stu开发者_高级运维dio 2005.
I was converting some of my source code to C#.
However, when I was doing the code snippet below, I noticed I don't have the IsNumber method.
Why is the IsNumber missing? I wanted to use it so that I can force a user to enter only numbers.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar.IsNumber(e.KeyChar) = False Then
e.Handled = True
End If
End Sub
Many thanks for any suggestions,
use the static char.IsNumber()
:
char.IsNumber(e.KeyChar);
By the way, I think you want to use char.IsDigit()
instead. This comes from the MSDN site:
IsNumber()
determines if a Char is of any numeric Unicode category. This contrasts withIsDigit()
, which determines if a Char is a radix-10 digit.
In other words, IsNumber()
also returns true for non-western numbers like 六 (Chinese '6').
C# is more strict in allowing you to call shared members on an instance variable.
Your original code gives me a warning in VB.
Warning 1 Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
In C# - it's just not allowed. Your solution to use char.IsNumber
is the way to go; and that code will work the same in either language.
public class Example1
{
public static int Test() { return 0; }
public Example1()
{
this.Test(); // This doesn't work
Example1.Test(); // This does
}
}
Solved.
Used the following:
if (char.IsNumber(e.KeyChar) == false)
{
e.Handled = true;
}
we normally use developer fusion to convert code from vb.net to c# and vice-versa. you can also try it.
精彩评论