传递null参数传递给C#方法 [英] Passing null arguments to C# methods
问题描述
有没有一种方法来传递空参数到C#方法(类似于C ++中的空参数)
例如:
是否可以翻译下面的C ++函数到C#方法:
私人无效例(INT * ARG1 ,为int * ARG2)
{
如果(ARG1 == NULL)
{
//做些什么
}
如果(ARG2 == NULL)
{
//做别的事情
}
}
是的。有两种类型的.NET:引用类型和值类型
引用类型(一般类)总是被引用提及,所以他们没有任何支持空加班。这意味着,如果一个变量的类型是引用类型,变量将自动为参考。
值类型(例如,INT)默认情况下没有空的概念。然而,对于它们的包装称为可为空。这使您可以封装非空的值类型,包括空的信息。
用法略有不同,虽然。
//这两种类型的意思是一样的东西,?只是C#的简写。
私人void示例(INT ARG1,可为空< INT> ARG2)
{
如果(arg1.HasValue)
DoSomething的();
ARG1 = NULL; //有效。
ARG1 = 123; //也是有效的。
DoSomethingWithInt(ARG1); // 无效!
DoSomethingWithInt(arg1.Value); //有效。
}
Is there a way to pass null arguments to C# methods (something like null arguments in c++)?
For example:
Is it possible to translate the following c++ function to C# method:
private void Example(int* arg1, int* arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
Yes. There are two kinds of types in .NET: reference types and value types.
References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.
Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.
The usage is slightly different, though.
// Both of these types mean the same thing, the ? is just C# shorthand.
private void Example(int? arg1, Nullable<int> arg2)
{
if (arg1.HasValue)
DoSomething();
arg1 = null; // Valid.
arg1 = 123; // Also valid.
DoSomethingWithInt(arg1); // NOT valid!
DoSomethingWithInt(arg1.Value); // Valid.
}
这篇关于传递null参数传递给C#方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!