C# 运行 转换方法而不是实际方法
C# Running Casted Method Instead of Actual Method
我有扩展单个 ViewComponent 的 ViewComponent 类型 class。在我的视图中,我让它遍历 ViewComponents 并打印它们。不幸的是,它提取的是强制转换的方法,而不是实际的 class 方法。例如:
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
}
}
}
如何让按钮打印 "Button" 而不是 "Component"?
您正在定义两个单独的实例方法,Component.getType()
和 ButtonComponent.getType()
。您很可能也收到了关于此的编译器警告,其效果为 "Method ButtonComponent.getType()
hides method from base class. Use the new
keyword if this is intended." 此警告让您了解您正在经历的行为,并且还有一个 page about it in the documentation。
您要做的是在基础 class 和 override
基础上声明一个 virtual
方法 class:
class Component {
public virtual string getType() {
return "Component";
}
}
class ButtonComponent: Component {
public override string getType() {
return "Button";
}
}
这样 ButtonComponent.getType()
的实现替换了 基本类型的实现。
旁注:一般来说,公认的方法名称约定是 PascalCase(不是驼峰命名法)。考虑将您的方法 GetType()
重命名为大写 G.
使用虚拟和覆盖关键字:
class Component {
public virtual string getType() {
return "Component";
}
}
class ButtonComponent: Component {
public override string getType() {
return "Button";
}
}
:)
我有扩展单个 ViewComponent 的 ViewComponent 类型 class。在我的视图中,我让它遍历 ViewComponents 并打印它们。不幸的是,它提取的是强制转换的方法,而不是实际的 class 方法。例如:
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
}
}
}
如何让按钮打印 "Button" 而不是 "Component"?
您正在定义两个单独的实例方法,Component.getType()
和 ButtonComponent.getType()
。您很可能也收到了关于此的编译器警告,其效果为 "Method ButtonComponent.getType()
hides method from base class. Use the new
keyword if this is intended." 此警告让您了解您正在经历的行为,并且还有一个 page about it in the documentation。
您要做的是在基础 class 和 override
基础上声明一个 virtual
方法 class:
class Component {
public virtual string getType() {
return "Component";
}
}
class ButtonComponent: Component {
public override string getType() {
return "Button";
}
}
这样 ButtonComponent.getType()
的实现替换了 基本类型的实现。
旁注:一般来说,公认的方法名称约定是 PascalCase(不是驼峰命名法)。考虑将您的方法 GetType()
重命名为大写 G.
使用虚拟和覆盖关键字:
class Component {
public virtual string getType() {
return "Component";
}
}
class ButtonComponent: Component {
public override string getType() {
return "Button";
}
}
:)