[英]How do I check if a value is assigned to an int in c#?
int x
might not have an assignment. int x
可能没有分配。 How do I detect that? 如何检测到? What value does int hold when it is unassigned?
取消分配int时,它保持什么值?
This gives me a warning in Visual Studio: 这给我在Visual Studio中的警告:
public SomeMethod(int x) {
if (x == null) {
/* VS throws a warning:
'The result of the expression is always 'false' since a value of type 'int'
is never equal to 'null' of type 'int' */
};
}
This also gives me a warning in Visual Studio: 这也给我在Visual Studio中的警告:
public SomeMethod(int? x) {
// declaring int 'Nullable' does not fix the warning.
if (x == null) {
// Same warning.
};
}
Likewise: 同样地:
public SomeMethod(int? x) {
if (!x.HasValue) {
// This does not work either.
};
}
int x might not have an assignment.
int x可能没有分配。
That's simply not true. 那根本不是真的。 In your case,
x
is a parameter - it's "definitely assigned" from the start of the method, in specification terminology. 在您的情况下,
x
是一个参数-在规范术语中,它是从方法开始时“确定分配”的。 When someone calls the method, they have to provide a value. 当有人调用该方法时,他们必须提供一个值。 There's no concept of the value not being assigned.
没有未分配值的概念。
If you want to represent a parameter which may not have a meaningful int
value, you should use Nullable<int>
, aka int?
如果要表示一个可能没有有意义的
int
值的参数,则应使用Nullable<int>
,也称为int?
: :
public void DoSomething(int? x)
{
if (x == null)
{
...
}
else
{
// Or whatever
Console.WriteLine(x.Value);
}
}
As of C# 4, you could then give the parameter a default value of null
if you want to be able to call it as just foo.DoSomething()
without providing a value. 从C#4开始,如果希望仅作为
foo.DoSomething()
调用而不提供值,则可以将参数的默认值设置为null
。 You couldn't distinguish between that and foo.DoSomething(null)
though. 你不能区分那个和
foo.DoSomething(null)
。
In your case the best solution probably would be to use a default value for the parameter like this, so that when the parameter is null, the code does not throw an error and also the compiler will not show any warning - 在您的情况下,最好的解决方案可能是对像这样的参数使用默认值,以便当参数为null时,代码不会引发错误,并且编译器也不会显示任何警告-
public void test(int? x){
if (x == null)
{
Console.Write("test");
}
}
public void testA(int? x = null)
{
if (x == null)
{
Console.Write("test");
}
}
static void Main(string[] args)
{
var p = new Program();
p.test(null);
p.testA();
}
But the code - 但是代码-
public SomeMethod(int x) {
if (x == null) {
/* Never happens because 'The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int' */
};
}
will always show warning because the default value for int
is 0
, not null
as mentioned here - 将始终显示警告,因为默认值
int
是0
,而不是null
这里提到-
And thus the the value for x == null
is always false. 因此,
x == null
值始终为false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.