[英]Do inheritances automatically get inherited by all child classes in C#
Something I was just testing with a simple using() statement.我只是用一个简单的 using() 语句测试的东西。
Got 2 classes: Child and Parent有2个班级:孩子和父母
public class Parent : IDisposable
{
public void Dispose()
{
// disposing stuff
}
}
public class Child : Parent
{
public void Dispose()
{
// disposing stuff
}
}
Now when I start using Using() statements:现在,当我开始使用 Using() 语句时:
using(Parent = new Parent()){}
Dispose does get called for Parent Dispose 确实被 Parent 调用
using(Child = new Child()){}
Dispose isn't called未调用 Dispose
Unless I specifically add:除非我特别添加:
public class Child : Parent, IDisposable
Or am I overlooking something?还是我忽略了什么?
I'm assuming your Dispose
method is not virtual
and you also have a Dispose
method in Child
.我假设您的
Dispose
方法不是virtual
的,并且您在Child
中也有一个Dispose
方法。 The problem is that when you cast Child
to IDisposable
(which using
does implicitly), then the compiler is binding to the Dispose
method in Parent
, since that's the type that implements IDisposable
.问题是,当您将
Child
转换为IDisposable
( using
隐式执行)时,编译器将绑定到Parent
中的Dispose
方法,因为这是实现IDisposable
的类型。 If Dispose
were virtual
, then at runtime the binder would look for an override of Dispose
in the Child
class and call that.如果
Dispose
是virtual
,那么在运行时活页夹将在Child
class 中寻找Dispose
的重写并调用它。
public class Parent : IDisposable
{
public virtual void Dispose()
{
Console.WriteLine("In Disposed");
}
}
public class Child : Parent
{
public override void Dispose()
{
Console.WriteLine("In Child Disposed");
}
}
Or, if Child
implements IDisposable
(which seems redundant), then the cast to IDisposable
would bind to the Dispose
method on Child
instead of Parent
.或者,如果
Child
实现了IDisposable
(这似乎是多余的),那么对IDisposable
的转换将绑定到Child
而不是Parent
上的Dispose
方法。
public class Parent : IDisposable
{
public void Dispose()
{
Console.WriteLine("In Disposed");
}
}
public class Child : Parent, IDisposable
{
public void Dispose()
{
Console.WriteLine("In Child Disposed");
}
}
Note that in either case you should call the parent's Dispose
method from the child Dispose
method, whether you are overriding or implementing the interface yourself.请注意,在任何一种情况下,您都应该从子
Dispose
方法调用父级的Dispose
方法,无论您是重写接口还是自己实现接口。 That way you ensure that any unmanaged resources held by the parent class get disposed as well.这样您就可以确保父 class 持有的任何非托管资源也得到处置。
public override void Dispose()
{
Console.WriteLine("In Child Disposed");
base.Dispose();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.