[英]If-statement GetType() c#
if I have int number in nominator, I will do one method from my1.cs, if I have double number in nominator/denominator I will do method from another class called my2.cs.如果我在提名者中有整数,我将从 my1.cs 执行一种方法,如果我在提名者/分母中有双数,我将从另一个名为 my2.cs 的 class 执行方法。 How I may code IF,
我如何编码 IF,
if (number = int) {//; bla bla bla...}
if (number = int) {//; bla bla bla...}
OR if (number = int) {//; bla bla bla...}
或
if (number = double) {//; bla bla bla...}
How to code this if-statement: if (numerator.GetType==int){...}
?如何编写这个 if 语句:
if (numerator.GetType==int){...}
?
The main trouble is in this: I read nominator and denominator from textbox, with var dr1 = textBox1.Text.Split('/');主要的麻烦在于:我从文本框中读取了提名者和分母, var dr1 = textBox1.Text.Split('/'); , split?
, 分裂? but how i can gettype from string???
但是我如何从字符串中获取类型???
if (numerator is int) { ... }
or或者
if (numerator.GetType() == typeof(int)) {...}
The former is usually better.前者通常更好。
EDIT: Нou say the problem is parsing numbers from string representation.编辑:Нou 说问题是从字符串表示中解析数字。 I'm afraid, the best approach here is to call
type.TryParse
and check if given string can be parsed as a number of given type.恐怕,这里最好的方法是调用
type.TryParse
并检查给定的字符串是否可以解析为给定类型的数量。
Eg例如
var tokens = line.Split('/');
double dArg1,dArg2; int iArg1, iArg2;
if (int.TryParse(tokens[0], out iArg1)
&& int.TryParse(tokens[1], out iArg2)){
return iArg1/iArg2;
} else if (double.TryParse(tokens[0], out dArg1)
&& double.TryParse(tokens[1], out dArg2)){
return dArg1/dArg2;
} else { /* handle error */ }
Note that all int
s can be parsed as double
s, so you need to try to parse token as int
before trying to parse it as `double.请注意,所有
int
都可以解析为double
,因此您需要尝试将 token 解析为int
,然后再尝试将其解析为 `double.
if (numerator.GetType() == typeof(int))
{
...
}
You can use the typeof-operator:您可以使用 typeof 运算符:
if(typeof(int) == numerator.GetType())
{
//put code here
}
You should try the is/as operator:您应该尝试 is/as 运算符:
if (numerator is int) {...}
Use theis operator in C# .在 C# 中使用is运算符。
if(number is int)
Use the following:使用以下内容:
if ( value is int ) { }
You may also want to take a look at Generic Methods (C# Programming Guide)您可能还想看看通用方法(C# 编程指南)
C# 7 C# 7
if (number is int myint) {//; do something with myint} OR
if (number is double mydouble) {//; do something with mydouble}
Each case is true if the type matches.如果类型匹配,则每种情况都为真。 The cast value will be placed in the variable.
转换值将被放置在变量中。
This should work:这应该有效:
if (numerator.GetType() == typeof(int))
{
// it's an int
}
else if (numerator.GetType() == typeof(double))
{
// it's a double
}
Not sure why you'd want to do that though...不知道你为什么要这样做......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.