在父 class 中使用 C# ref 时出现问题
Problem with C# ref when used in parent class
我有摘要class
public abstract class BaseType
{
public BaseType(int offset)
{
TestRef(ref offset);
}
protected abstract void TestRef(ref int offset);
}
和派生类型,
public class DerivedType : BaseType
{
public DerivedType(int offset) : base(offset)
{
Console.WriteLine($"ctor: increasing offset: {++offset}");
}
protected override void TestRef(ref int offset)
{
Console.WriteLine($"TestRef: increasing offset: {++offset}");
}
}
还有一个主要实例化派生类型的地方:
public static void Main()
{
var dt = new DerivedType(0);
}
我假设因为 TestRef
引用了 offset
,所以我会看到 TestRef
添加的变化。换句话说,我会期待下面的输出,
TestRef: increasing offset: 1
ctor: increasing offset: 2
但我得到了
TestRef: increasing offset: 1
ctor: increasing offset: 1
我做错了什么?
通过 base(offset) 传递给基 class 的构造函数参数按值传递给基 class,而不是按引用传递。
您不能通过引用传递构造函数参数。
如果我对你的问题的理解正确,要实现你想要的行为,你需要在所有调用中始终按引用传递整数,如下所示:
public abstract class BaseType
{
public BaseType(ref int offset)
{
TestRef(ref offset);
}
protected abstract void TestRef(ref int offset);
}
public class DerivedType : BaseType
{
public DerivedType(ref int offset) : base(ref offset)
{
Console.WriteLine($"ctor: increasing offset: {++offset}");
}
protected override void TestRef(ref int offset)
{
Console.WriteLine($"TestRef: increasing offset: {++offset}");
}
}
public static void Main()
{
var dt = new DerivedType(ref 0);
}
我有摘要class
public abstract class BaseType
{
public BaseType(int offset)
{
TestRef(ref offset);
}
protected abstract void TestRef(ref int offset);
}
和派生类型,
public class DerivedType : BaseType
{
public DerivedType(int offset) : base(offset)
{
Console.WriteLine($"ctor: increasing offset: {++offset}");
}
protected override void TestRef(ref int offset)
{
Console.WriteLine($"TestRef: increasing offset: {++offset}");
}
}
还有一个主要实例化派生类型的地方:
public static void Main()
{
var dt = new DerivedType(0);
}
我假设因为 TestRef
引用了 offset
,所以我会看到 TestRef
添加的变化。换句话说,我会期待下面的输出,
TestRef: increasing offset: 1
ctor: increasing offset: 2
但我得到了
TestRef: increasing offset: 1
ctor: increasing offset: 1
我做错了什么?
通过 base(offset) 传递给基 class 的构造函数参数按值传递给基 class,而不是按引用传递。 您不能通过引用传递构造函数参数。
如果我对你的问题的理解正确,要实现你想要的行为,你需要在所有调用中始终按引用传递整数,如下所示:
public abstract class BaseType
{
public BaseType(ref int offset)
{
TestRef(ref offset);
}
protected abstract void TestRef(ref int offset);
}
public class DerivedType : BaseType
{
public DerivedType(ref int offset) : base(ref offset)
{
Console.WriteLine($"ctor: increasing offset: {++offset}");
}
protected override void TestRef(ref int offset)
{
Console.WriteLine($"TestRef: increasing offset: {++offset}");
}
}
public static void Main()
{
var dt = new DerivedType(ref 0);
}