C#使用泛型转换调用阴影方法 [英] C# Call shadow method with generic cast

查看:90
本文介绍了C#使用泛型转换调用阴影方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个将对象转换为泛型类型来执行特定阴影方法的方法。这是我的测试代码:

  class程序
{
static void Main(string [] args)
{
hello2 h2 = new hello2();
test(h2);
Console.ReadLine();
}

static void test(hello h)
{
h.write2< hello2>();


$ b $ class hello
{
public virtual void write()
{
Console.WriteLine(hello );
}

public void write2< T>()其中T:hello
{
T h2 =(T)this;
hello2 h21 =(hello2)this;
h2.write();
h21.write();


$ b $ class hello2:hello
{
public new void write()
{
Console.WriteLine hello2);


我的控制台输出是:



hello

hello2



我调试了它, t发现一个错误。在这两种情况下,输出都应该是hello2。我在这里错过了很明显的东西吗或者这只是不工作?

解决方案

你缺少的是被调用的方法是在编译时选择的 hello 不使用 write2 。所以在编译时编译器知道 T 是类型 hello 或其他派生类,所以它选择了因为这是它在编译时知道的唯一方法。



想想这样,将每个 T 与任何位于右侧的内容相关联。这是编译器看到并使用该信息做出选择的内容。

  //编译器在编译时看到的内容即使你传入hello2作为T. 
public void write2< T>()其中T:hello
{
hello h2 =(hello)this;
hello2 h21 =(hello2)this;
h2.write();
h21.write();
}


I'm trying to write a method which casts an object to a generic type to execute a specific shadow method. This is my test code:

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");
    }
}

My Console Output is:

hello

hello2

I debugged it, checked everything and couldn't find a mistake. The Output should be hello2 in both cases. Am I missing something obvious here? Or is this just not working?

解决方案

The thing you are missing is the method that is called is chosen at the compile time of hello not at the use of write2. So at compile time all the compiler knows is that T is of type hello or some other derived class so it chooses the shadowed method as that is the only method it knows about at compile time.

Think of it this way, replace every T with whatever is on the right side of the :. This is what the compiler sees and uses that information to make its choices.

//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#使用泛型转换调用阴影方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆