加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 继承自struct

发布时间:2020-12-15 04:16:50 所属栏目:百科 来源:网络整理
导读:我试图弄清楚我的代码是什么问题. 我有这个代码: public struct MyStructA{ public MyStructA(string str) { myString= str; } public string myString;}public struct MyStructB: MyStructA{ public string myReversString;} 我得到这个错误: Error at co
我试图弄清楚我的代码是什么问题.
我有这个代码:
public struct MyStructA
{
    public MyStructA(string str)
    {
        myString= str;
    }

    public string myString;
}

public struct MyStructB: MyStructA
{
    public string myReversString;
}

我得到这个错误:

Error at compile time: Type 'MyStructA' in interface list is not an interface

我不明白为什么? .net不是implemnet结构像类?

解决方法

结构隐含密封

根据这个link:

C#中的每个结构,无论是用户定义还是在.NET Framework中定义,都是密封的,这意味着您无法从其继承.结构是密封的,因为它是一个值类型,所有的值类型都是密封的.

一个结构体可以实现一个接口,所以可以在结尾的名字之后看到一个冒号后面的另一个类型名.

在下面的例子中,当我们尝试定义一个继承自上面定义的结构的新结构时,我们得到一个编译时错误.

public struct PersonName
{
    public PersonName(string first,string last)
    {
        First = first;
        Last = last;
    }

    public string First;
    public string Last;
}

// Error at compile time: Type 'PersonName' in interface list is not an interface
public struct AngryPersonName : PersonName
{
    public string AngryNickname;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读