C# 首先调用基类的构造函数
如果你得到了这样的东西:C# 首先调用基类的构造函数,c#,C#,如果你得到了这样的东西: public abstract class BaseFoo { public BaseFoo() { FooMethod(); } public abstract void FooMethod(); } public class Foo : BaseFoo { private Stream _stream; public Foo(Stream stream) { _stream
public abstract class BaseFoo
{
public BaseFoo()
{
FooMethod();
}
public abstract void FooMethod();
}
public class Foo : BaseFoo
{
private Stream _stream;
public Foo(Stream stream)
{
_stream = stream;
}
public override void FooMethod()
{
//do anything with the stream
_stream.Read(...);
//--> _stream = null
}
}
如你所见。有一个大问题。BaseFoo类的构造函数调用抽象方法FooMethod。在其实现中,它尝试访问_流字段。但是_流为null,因为执行了Foo类的ctor
是否有任何可能性或模式,以解决这种情况(我可以更改为基类)。我只是在寻找一个好的解决办法
有可能做那样的事吗
public Foo(Stream stream)
{
_stream = stream;
base();
}
如果有人有主意就好了 正是因为你问题中概述的原因
构造完成后调用
FooMethod
方法。初始化继承的类时,还需要先初始化其基类。如果将构造函数更改为具有一些可接受的参数(即删除默认构造函数),您将能够很容易地看到这一点:
在这种情况下,代码不会编译,因为Foo类会说BaseFoo不包含无参数构造函数,您需要调用它。此外,这不是无参数构造函数的目的
我可以想出一个解决办法,但它不是很好,你可能想用另一种方式。但如果你真的不这样做,你可以做如下事情:
public abstract class BaseFoo
{
private Action toRunOnConstruct;
public BaseFoo(Action toRunOnConstruct)
{
this.toRunOnConstruct = toRunOnConstruct;
toRunOnConstruct.Invoke();
}
}
public class Foo : BaseFoo
{
private Stream _stream;
public Foo(Stream stream) : base(()=> SomethingToDoWithTheStream(stream))
{
_stream = stream;
}
public static void SomethingToDoWithTheStream(Stream stream)
{
//do anything with the stream
stream.Read(...);
//--> _stream = null
}
CA2214:不要在构造函数中调用可重写的方法。你想实现什么?从你的例子看不清楚阅读这个问题的答案,它解释了初始化器和构造函数是如何运行的
public abstract class BaseFoo
{
private Action toRunOnConstruct;
public BaseFoo(Action toRunOnConstruct)
{
this.toRunOnConstruct = toRunOnConstruct;
toRunOnConstruct.Invoke();
}
}
public class Foo : BaseFoo
{
private Stream _stream;
public Foo(Stream stream) : base(()=> SomethingToDoWithTheStream(stream))
{
_stream = stream;
}
public static void SomethingToDoWithTheStream(Stream stream)
{
//do anything with the stream
stream.Read(...);
//--> _stream = null
}