2

我是 c# 编程的新手,我知道这是一个业余问题,所以请不要笑我!

我是声明这些接口

class derived : iInterface3
{
    double[] d = new double[5];
    public override int MyProperty
    {
        get
        {
            return 5;
        }
        set
        {
            throw new Exception();
        }
    }
    int iProperty
    {
        get
        {
            return 5;
        }
    }
    double this[int x]
    {
        set
        {
            d[x] = value;
        }
    }
}
class derived2 : derived
{

}
interface iInterface
{
    int iProperty
    {
        get;
    }
    double this[int x]
    {
        set;
    }
}
interface iInterface2 : iInterface
{ }
interface iInterface3 : iInterface2
{ }

即使我将 iInterface 的所有成员都实现为派生类,但我仍然收到此错误。

“final_exam_1.derived”没有实现接口成员“final_exam_1.iInterface.this[int]”。'final_exam_1.derived.this[int]' 无法实现接口成员,因为它不是公共的。

和这个

“final_exam_1.derived”没有实现接口成员“final_exam_1.iInterface.iProperty”。“final_exam_1.derived.iProperty”无法实现接口成员,因为它不是公共的。

为什么?

提前感谢您的帮助!

4

4 回答 4

3

您需要将public 访问修饰符添加到从该类派生的所有成员。

默认情况下,他们的访问权限较低。

此外,您需要删除override,因为在实现接口时没有需要覆盖的内容。覆盖是当您希望覆盖一个虚拟方法时。

class derived : iInterface3
{
    double[] d = new double[5];

    public int MyProperty
    {
        get
        {
            return 5;
        }
        set
        {
            throw new Exception();
        }
    }

    public int iProperty
    {
        get
        {
            return 5;
        }
    }

    public double this[int x]
    {
        set
        {
            d[x] = value;
        }
    }
}

您的代码还有其他问题,但这些都是无法编译的原因。

于 2013-01-12T18:08:52.473 回答
0

使iProperty索引器公开或使用显式接口实现。显式实现的声明如下所示:int iInterface3.iProperty.

于 2013-01-12T18:09:37.697 回答
0

你不能overrideproperty int MyProperty,因为没有什么可以覆盖的。没有int MyProperty在基地class/interface

于 2013-01-12T18:11:01.810 回答
0

哟确实有很多愚蠢的问题

    public override int MyProperty
    {
        get
        {
            return 5;
        }
        set
        {
            throw new Exception();
        }
    }

因为您是从接口实现的,而不是已经具有虚拟成员的基类/抽象类,因此覆盖是没有意义的。

第二题。

    int iProperty
    {
        get
        {
            return 5;
        }
    }

继承的属性不能是私有类型。

固定代码:

class derived : iInterface3
{
    readonly double[] d = new double[5];
    public int MyProperty
    {
        get
        {
            return 5;
        }
        set
        {
            throw new Exception();
        }
    }

    public int iProperty
    {
        get
        {
            return 5;
        }
    }

    public double this[int x]
    {
        set
        {
            d[x] = value;
        }
    }
}
class derived2 : derived
{

}
interface iInterface
{
    int iProperty
    {
        get;
    }
    double this[int x]
    {
        set;
    }
}
interface iInterface2 : iInterface
{ }
interface iInterface3 : iInterface2
{ }
于 2013-01-12T18:12:38.037 回答