我想从另一个类 A
中初始化一个类型为 B
的对象,为什么我仍然得到 null?是否可以在不使用 ref
和 out
修饰符的情况下做到这一点?
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/