为什么在结构上允许接口继承,为什么不能继承类

 无为2502863873 发布于 2023-02-09 20:56

在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#:结构和接口

1 个回答
  • 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#:结构和接口

    2023-02-09 21:04 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有