在C#中,结构是值类型,接口和类都是引用类型.那么,为什么struct不能继承一个类,但它可以继承一个接口?
class a { } public struct MyStruct : a //This will not be allowed. { } interface a { } public struct MyStruct : a // and this will work { }
Tigran.. 11
Interface
它本身不是引用或值类型.Interface
是一个合约,其引用或价值类型订阅.
你可能会提到一个事实,struct
即继承自 interface
盒装.是.这是因为在C#中,struct成员被定义为virtual
成员.对于虚拟成员,您需要维护虚拟表,因此需要引用类型.
让我们按照以下方式证明这一点:
public interface IStruct { string Name {get;set;} } public struct Derived : IStruct { public string Name {get;set;} }
现在,我们以这种方式调用它:
//somewhere in the code public void ChangeName(IStruct structInterface) { structInterface.Name = "John Doe"; } //and we call this function as IStruct inter = new Derived(); ChangeName(inter); //HERE NAME IS CHANGED !! //inter.Name == "John Doe";
这不是我们对值类型的期望,但这与引用类型的工作方式完全相同.所以这里发生的是Derived的值类型实例被装箱到在其上构造的引用类型IStruct
.
在这种情况下,性能影响以及误导性行为(例如,开始表现为引用类型的值类型).
有关此主题的更多信息,请查看:
C#:结构和接口
Interface
它本身不是引用或值类型.Interface
是一个合约,其引用或价值类型订阅.
你可能会提到一个事实,struct
即继承自 interface
盒装.是.这是因为在C#中,struct成员被定义为virtual
成员.对于虚拟成员,您需要维护虚拟表,因此需要引用类型.
让我们按照以下方式证明这一点:
public interface IStruct { string Name {get;set;} } public struct Derived : IStruct { public string Name {get;set;} }
现在,我们以这种方式调用它:
//somewhere in the code public void ChangeName(IStruct structInterface) { structInterface.Name = "John Doe"; } //and we call this function as IStruct inter = new Derived(); ChangeName(inter); //HERE NAME IS CHANGED !! //inter.Name == "John Doe";
这不是我们对值类型的期望,但这与引用类型的工作方式完全相同.所以这里发生的是Derived的值类型实例被装箱到在其上构造的引用类型IStruct
.
在这种情况下,性能影响以及误导性行为(例如,开始表现为引用类型的值类型).
有关此主题的更多信息,请查看:
C#:结构和接口