【发布时间】:2014-08-11 14:09:51
【问题描述】:
我正在尝试编写一个将对象转换为泛型类型以执行特定影子方法的方法。这是我的测试代码:
class Program
{
static void Main(string[] args)
{
hello2 h2 = new hello2();
test(h2);
Console.ReadLine();
}
static void test(hello h)
{
h.write2<hello2>();
}
}
class hello
{
public virtual void write()
{
Console.WriteLine("hello");
}
public void write2<T>() where T : hello
{
T h2 = (T)this;
hello2 h21 = (hello2)this;
h2.write();
h21.write();
}
}
class hello2 : hello
{
public new void write()
{
Console.WriteLine("hello2");
}
}
我的控制台输出是:
你好
你好2
我调试了它,检查了一切,没有发现错误。在这两种情况下,输出都应该是 hello2。我在这里遗漏了一些明显的东西吗?或者这只是不起作用?
【问题讨论】:
-
使用
override而不是new。 -
@Selman22 这并不能解释为什么目前它没有输出“hello2”。
-
这只是一个示例。在我的情况下,我不能使用覆盖。