C# 使用泛型转换调用影子方法

标签 c# generics shadow

我正在尝试编写一种将对象转换为泛型类型以执行特定影子方法的方法。这是我的测试代码:

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。我在这里遗漏了一些明显的东西吗?还是这根本不起作用?

最佳答案

您缺少的是被调用的方法是在 hello 的编译时选择的,而不是在使用 write2 时选择的。所以在编译时,编译器只知道 Thello 类型或其他派生类,所以它选择隐藏方法,因为这是它在编译时唯一知道的方法编译时间。

这样想,将每个 T 替换为 : 右侧的任何内容。这就是编译器看到并使用该信息做出选择的内容。

//What the complier sees when you compile even if you pass in hello2 as T.
public void write2<T>() where T : hello
{
    hello h2 = (hello)this;
    hello2 h21 = (hello2)this;
    h2.write();
    h21.write();
}

关于C# 使用泛型转换调用影子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25245322/

相关文章:

c# - 具有透明填充但实线描边的 WPF 形状可能吗?

c# - F# 2.0 中的错误与泛型类型参数的约束在哪里有关?

c# - 使用反射将项目添加到通用列表/集合

ios - 检测 UIView 在动画期间何时更改大小以使阴影移动

c# - 如何将二维 float 组转换为字节数组,反之亦然

C# mysql 查询if语句

c# - 将目标强制转换为 IEnumerable 时,莫清 GetEnumerable 失败

c# - 以类型泛型/不可知的方式实现泛型方法的最佳方法

html - 如何在 html 上的实际屏幕框架上添加阴影?

css - Iphone 上的元素的阴影无法正常工作