【问题标题】:Can i access a concrete method of an abstract class in direct child class?我可以在直接子类中访问抽象类的具体方法吗?
【发布时间】:2013-04-20 09:48:44
【问题描述】:

有没有一种方法可以在直接子类中访问抽象类的具体方法,如下所示

  abstract class ParameterBase
  {           
        public void test()
        { 
            string name = "testname";
            console.writeline(name);
        }          
  }

  public  class Parameter1 : ParameterBase 
  {
       //I Need to call(access) the Test() Method here i.e print "testname" in the  console         
  }

现在我知道我们可以创建一个类型为 ParameterBase 的子类的实例,并访问 ParameterBase( )如下

   ParameterBase PB = new Parameter1();
   PB.test();

【问题讨论】:

  • 你可以访问所有不是private的基类方法。记住 - 子类 IS A 基类。
  • @lazyberezovsky :谢谢,但我怎么称呼它。你能举个例子吗
  • 您可以使用test() 调用它。 C# 会尝试解析这个名称,在 Parameter1 类中找不到它,然后尝试在基类中找到它,并且可以在 ParameterBase 类中找到它。

标签: c# .net abstract-class abstraction


【解决方案1】:

您必须在继承类时保持可访问性级别。你可以这样做:

abstract class ParameterBase
{
    public void test()
    {
        string name = "testname";
        Console.WriteLine(name);
    }
}

class Parameter1 : ParameterBase
{
    void getvalue()
    {
        Parameter1 pb = new Parameter1();
        pb.test();
    }        
}  

【讨论】:

    【解决方案2】:

    请看这个:-

    class Program
    {
        static void Main(string[] args)
        {
            Test2 t = new Test2();
            t.display();
            t.absDsisplay();
        }
    }
    
    abstract class Test1
    {
        public void display()
        {
            Console.WriteLine("display");
        }
        public abstract void absDsisplay();
    
    }
    class Test2 : Test1
    {
    
        void GetValu()
        {
    
    
        }
    
        public override void absDsisplay()
        {
            Console.WriteLine("absDisplay");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      相关资源
      最近更新 更多