gpt4 book ai didi

C# 运行类型转换方法而不是实际方法

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:20 25 4
gpt4 key购买 nike

我有一些扩展单个 ViewComponent 类的 ViewComponents 类型。在我的 View 中,我让它遍历 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
}
}
}

如何让按钮打印“Button”而不是“Component”?

最佳答案

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

您要做的是在基类上声明一个虚拟方法并在子类中覆盖它:

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

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

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


旁注:一般来说,公认的方法名称约定是 PascalCase(而不是驼峰命名法)。考虑使用大写 G 重命名您的方法 GetType()

关于C# 运行类型转换方法而不是实际方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31868148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com