为什么允许对结构进行接口继承,为什么不能继承类



在C#中,结构是值类型,接口和类都是引用类型。那么,为什么struct不能继承类,而可以继承接口呢?

class a { }
public struct MyStruct : a //This will not be allowed.
{
}
interface a { }
public struct MyStruct : a  // and this will work
{
}

Interface本身不是引用或值类型。Interface合同,其引用或值类型订阅。

您可能提到了一个事实,即从interface继承的struct已装箱。对这是因为在C#中,结构体成员的定义类似于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#:结构和接口

接口不是值或引用类型。事实上,我相信它是唯一一个继承自.Net框架中Object基类型的构造。

请参阅MSDN链接

最新更新