【问题标题】:C# Running Casted Method Instead of Actual MethodC# 运行转换方法而不是实际方法
【发布时间】:2015-08-07 01:07:08
【问题描述】:

我拥有扩展单个 ViewComponent 类的 ViewComponents 类型。在我的视图中,我让它遍历 ViewComponents 并打印它们。不幸的是,它拉的是铸造方法而不是实际的类方法。例如:

using System;

namespace test
{
  class Component {
    public string getType() {
      return "Component";
    }
  }

  class ButtonComponent: Component {
    public string getType() {
      return "Button";
    }
  }

  public class test
  {
    public static void Main() {
      Component[] components = new Component[1];
      components [0] = new ButtonComponent();

      Console.WriteLine(components[0].getType()); // prints Component
    }
  }
}

如何让按钮打印“按钮”而不是“组件”?

【问题讨论】:

    标签: c# class methods overriding


    【解决方案1】:

    您正在定义两个单独的实例方法,Component.getType()ButtonComponent.getType()。您很可能也收到了关于此的编译器警告,类似于“方法ButtonComponent.getType() 隐藏基类中的方法。如果有意,请使用new 关键字。”此警告旨在让您了解您所遇到的行为,并且还有一个 page about it in the documentation

    您想要做的是在基类上声明 virtual 方法并在子类中声明 override 它:

    class Component {
        public virtual string getType() {
          return "Component";
        }
    }
    
    class ButtonComponent: Component {
        public override string getType() {
          return "Button";
        }
    }
    

    这样ButtonComponent.getType()的实现替换了基类型的实现。


    旁注:通常,方法名称的公认约定是 PascalCase(不是 camelCase)。考虑使用大写 G 重命名您的方法 GetType()

    【讨论】:

      【解决方案2】:

      使用虚拟和覆盖关键字:

      class Component {
          public virtual string getType() {
             return "Component";
          }
      }
      
      class ButtonComponent: Component {
          public override string getType() {
              return "Button";
          }
      }
      

      :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-30
        • 1970-01-01
        • 1970-01-01
        • 2010-09-16
        • 1970-01-01
        相关资源
        最近更新 更多