你如何覆盖C#中的属性?

Oma*_*eji 2 c# inheritance

我有一个接口说IMyInterface是由MyClass类实现的,我怎么用getter和setter声明属性,覆盖而不是掩盖接口中的那些?

例如对于界面:

public interface IMyInterface
{
    String MyProperty {get;}
}
Run Code Online (Sandbox Code Playgroud)

如果我这样做,我隐藏了接口属性

public class MyClass : IMyInterface
{
    public String MyProperty 
    { 
        get 
        {
             return "Whatever";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我这样做,我会收到一条错误消息,指出MyProperty不能公开:

public class MyClass : IMyInterface
{
    public String IMyInterface.MyProperty 
    { 
        get 
        {
             return "Whatever";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*eid 5

由于接口没有实现,覆盖是一个不适用于接口的概念.因此,接口成员不需要virtual.

您在使用类继承时覆盖.您需要virtual在基类中创建它们,并override在子类中使用关键字:

interface IFoo
{
    string Bar { get; }
}

class FooBase : IFoo
{
    public virtual string Bar { get; protected set; }
}

class Foo : FooBase
{
    public override string Bar { get; protected set; }
}
Run Code Online (Sandbox Code Playgroud)

如果显式实现接口,则不需要public修饰符,因为只有当使用者使用接口类型时才能看到该成员:

class FooExplicit : IFoo
{
    // IFoo f = new FooExplicit(); <- Bar is visible
    // FooExplicit fe = new FooExplicit(); <- there is no Bar
    string IFoo.Bar { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

至于IFoo.Bar仍然只与界面有关,它仍然是隐含的public.在Java中,您可以根据需要添加public修饰符(当然是可选的).相反,C#禁止这样做.

  • 实际上你不能*覆盖*接口成员,但只能覆盖基类成员.您*实现*接口,并从基类重写*实现*. (7认同)