c# - 为什么我不能以相同的方式初始化对象(不使用 ref)?

标签 c# .net out ref

我想从另一个类 A 中初始化一个类型为 B 的对象,为什么我仍然得到 null?是否可以在不使用 refout 修饰符的情况下做到这一点?

    class A
    {
        public void Initialize(B value)
        {
            if (value == null)
            {
                value = new B();
            }
        }
    }

    class B
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = null;
            a.Initialize(b);
        }
    }

[upd.] 我认为 b 变量可以通过 ref 传递,因为它是类的实例。

最佳答案

这是可能的,只需将 Initialize() 设为一个函数即可:

class A
{
    public B Initialize(B value)
    {
        if (value == null)
        {
            value = new B();
        }
        return value;
    }
}

这样调用它:

    static void Main(string[] args)
    {
        A a = new A();
        B b = null;
        b = a.Initialize(b);
    }

这是一个很好的解决方案,数据流向清晰可见。没有惊喜。

但除此之外,只需使用 ref(不是 out):public void Initialize(ref B value) 并调用 a.Initialize(ref b);


I thought the b variable could be passed by ref because of it's the instance of the class.

要回答这个问题,您需要非常精确的措辞:b不是类的实例。 b 是对实例的引用。实例从来没有名字。

b 被视为值类型:引用按值传递给方法。除非你使用 ref

关于c# - 为什么我不能以相同的方式初始化对象(不使用 ref)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10205302/

相关文章:

c# - MVVM 使用工厂方法处理窗口管理

c# - 为什么在不影响其值的情况下允许在任何成员变量(即调用函数/属性)之前使用 '@'?

C# - 为什么我需要初始化一个 [Out] 参数

c# - Azure EventHub - EventHubClient.Send() 导致 NullReferenceException

c# - 选择不同的MongoDB C#

c# - 我可以查询 mysql DB 但无法保存对其的更改

.net - 64 位 Win 上缺少 dll

c# - 由于奇怪的错误,无法在 Visual Studio 2008 C# Windows 窗体中看到设计器 View

python - 将 ctypes c_void_p 转换为 C 输出参数

linux - 通过 ssh 与集群的从属节点连接失败