有没有办法将空参数传递给 C# 方法(类似于 C++ 中的空参数)?
Is there a way to pass null arguments to C# methods (something like null arguments in c++)?
例如:
是否可以将以下 C++ 函数转换为 C# 方法:
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 } } 推荐答案是的..NET 中有两种类型:引用类型和值类型.
Yes. There are two kinds of types in .NET: reference types and value types.
引用类型(通常是类)总是被引用引用,所以它们支持 null 而不需要任何额外的工作.这意味着如果变量的类型是引用类型,则该变量自动成为引用.
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.
值类型(例如 int)默认没有 null 的概念.但是,它们有一个名为 Nullable 的包装器.这使您能够封装不可为空的值类型并包含空信息.
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.
不过用法略有不同.
// 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. }更多推荐
将空参数传递给 C# 方法
发布评论