Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为方法中的参数赋值NULL_C# - Fatal编程技术网

C# 为方法中的参数赋值NULL

C# 为方法中的参数赋值NULL,c#,C#,我知道传递给方法的引用类型是可以修改的。但我发现它只对参数的成员有效,而对参数本身无效。下面是一个测试: 这是一种引用类型: class MyClass { public int PropInt { get; set; } public string PropStr { get; set; } public int FieldInt; public string FiledStr; } 此方法修改其成员: void MyFun(MyClass myClas

我知道传递给方法的引用类型是可以修改的。但我发现它只对参数的成员有效,而对参数本身无效。下面是一个测试:

这是一种引用类型:

class MyClass
{
    public int PropInt { get; set; }

    public string PropStr { get; set; }

    public int FieldInt;

    public string FiledStr;
}
此方法修改其成员:

void MyFun(MyClass myClass)
    {
        myClass.PropInt = 3;
        myClass.FieldInt = 4;
        myClass.PropStr = "c";
        myClass.FiledStr = "d";
    }
这会修改自身(空或新):

初始化:

MyClass myClass = new MyClass
        {
            PropInt = 1,
            FieldInt = 2,
            PropStr = "a",
            FiledStr = "b"
        };
测试:

这是怎么发生的?
在这种情况下,我必须使用
out/ref
吗?

这是因为参数中对象的引用在方法中保持不变(除非您显式重新指定)。仅更改其属性时,对原始实例没有影响。方法完成后,调用方仍然可以访问原始对象并查看更改的属性。参数中的原始实例与调用方传入的引用保持相同

当您使用新的或重新分配更改参数时,调用方永远不会意识到此更改,除非您使用
out
ref
更改方法签名

如果希望调用方知道方法中正在重新分配或实例化引用类型,则需要使用
ref
keywoard()对其进行修改

例如:

public void Foo(ref MyClass bar)
{
   // Caller will get this new instance back
   // after method completes.
   bar = new MyClass()
}
更改引用: 下面的示例将参数更改为某个预先存在的本地引用

private MyClass myLocalBar
public void Foo(ref MyClass bar)
{
   // Caller will get the modified reference
   bar = this.myLocalBar;
}
您还可以使用
out
()关键字执行类似操作。但与
ref
不同,
out
需要为
out
参数指定一个值。在对
out
参数赋值之前尝试完成该方法将生成编译器错误

public void Foo(out MyClass bar)
{
   // We must assign a value to bar
   bar = new MyClass()
}
以下内容将生成错误(取消注释要修复的最后一行)


out
参数始终保证调用方会返回新的/不同的引用。然而,
ref
告诉调用者该方法可能修改或不修改原始引用。

是的,您需要在本例中使用out/refcase@Diryboy我想知道为什么。当涉及引用类型时,它是否与指针相同?是的,您可以这样想。@Hassansar,因为myClass在
MyFun
中被修改,但不是
MyFunNull
谢谢您的详细解释!
private MyClass myLocalBar
public void Foo(ref MyClass bar)
{
   // Caller will get the modified reference
   bar = this.myLocalBar;
}
public void Foo(out MyClass bar)
{
   // We must assign a value to bar
   bar = new MyClass()
}
public void Foo(out MyClass bar)
{
   // We must assign a value to bar
   // Even null assignment is ok:
   // bar = null;
}