使用c#进行OOPS查询

Pan*_*kaj 2 c# oop interface

我对类和接口的实现有一些疑问

我有2个这样的课

Public Class A:IFinal
  {
      private string name=string.Empty;

        A()
        {
            name = "Pankaj";
        }

        public string MyName()
        {
            return name;
        }

        public string YourName()
        {
            return "Amit";
        }
   }

Public  Class B:IFinal
 {
     private string name=string.Empty;

        B()
        {
            name = "Amit";
        }

        public string GetNane()
        {
            return name;
        }

        public string YourName()
        {
            return "Joy";
        }
   }
Run Code Online (Sandbox Code Playgroud)

题:

  1. 现在我有一个接口IFinal,我想在类A和B中实现此接口,方法YourName()就像这样

    公共接口IFinal {

         string YourName();// Class A & Class B
    
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

是否有可能以这种方式实施?如果是,那么我如何在界面中声明YourName(),我该如何使用它?

  1. 是否可以在接口中声明虚方法?就像在类A和B中一样,我们有一个需要在接口中声明的虚方法.

Win*_*ith 5

您可以在实现中将方法设为虚拟,例如:

interface IFinal
{
    string YourName();
}

class A: IFinal
{
    public virtual string YourName() { return "Amit"; }
}

class B: IFinal
{
    public virtual string YourName() { return "Joy"; }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用A和B派生的公共基础实现,例如

interface IFinal
{
    string YourName();
}

abstract class FinalBase : IFinal
{
    public virtual string YourName() { return string.Empty; }
}

class A : FinalBase
{
    public override string YourName()
    {
        return "A";
    }
}

class B : FinalBase
{
    public override string YourName()
    {
        return "B";
    }
}

class C : A
{
    public override string YourName()
    {
        return "C";
    }
}

new A().YourName(); // A
new B().YourName(); // B

IFinal b = new B();
b.YourName(); // B

FinalBase b = new C();
b.YourName(); // C
Run Code Online (Sandbox Code Playgroud)