从结构继承 [英] Inherit from struct

查看:135
本文介绍了从结构继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出是什么问题我丝毫code。 我有这个code:

I am try to figure out what is the problem whit my code. I have this code:

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结构像类?

I don't understand why? the .net not implemnet struct like class?

推荐答案

一个结构是隐式密封的

根据这一链接

在C#中的每个结构,无论是用户定义的,或在.NET Framework中定义的,是密封的,这意味着你不能继承它。一个结构是密封的,因为它是一个值类型,所有的值类型是密封的。

Every struct in C#, whether it is user-defined or defined in the .NET Framework, is sealed–meaning that you can’t inherit from it. A struct is sealed because it is a value type and all value types are sealed.

一个结构可以实现一个接口,所以可以看到另一种类型的名字跟在冒号后面,该结构的名称后。

A struct can implement an interface, so it’s possible to see another type name following a colon, after the name of the struct.

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

In the example below, we get a compile-time error when we try to define a new struct that inherits from the one defined above.

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;
}

这篇关于从结构继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆