通用重载解析 [英] Generic overload resolution

查看:90
本文介绍了通用重载解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情形:

 类Foo {}Foo类< T> :富{}

然后两个方法

 无效DoStuff(富富)
{
     DoStuffImpl(富);
}无效DoStuffImpl(富富)
{
     Console.WriteLine(A);
}
无效DoStuffImpl< T>(美孚< T>富)
{
     Console.WriteLine(B);
}无效的主要()
{
     DoStuff(新的Foo&所述; INT>()); //画的
}

(注意,code写的浏览器,但介绍我面临的形势)

我怎样才能得到它来调用泛型方法,并印片B?

这可以在所有完成,无需反思?我对如何可能与反思做一些想法,但是我正在寻找一个清洁的解决方案(如果存在)。

注:我不能让 DoStuff 通用的,因为这将与WCF和开放泛型类型是不允许使用

解决方案

(我假设你已经明白为什么会这样。如果没有,请阅读我的重载决议文章,并让我知道,如果它仍然不清楚。)

如果您正在使用C#4你的 的可以使用动态类型:

 无效DoStuff(富富)
{
    动态D = foo的;
    DoStuffImpl(四);
}

请注意这是如何不只是有一个动态参数 - 这个想法是,通过限制为类型或子类,我们的总是的有一个有效的 DoStuffImpl 打电话......它只是最好的方法将被确定执行时间,没有编译时间。

如果您是滞留在pre-C#4,你可能有双重分派做到这一点:

 类Foo
{
    公共虚拟无效CallStuffImpl(FooImplType X)
    {
        x.DoStuffImpl(本);
    }
}Foo类< T> :富
{
    公共覆盖无效CallStuffImpl(FooImplType X)
    {
        //看起来它是多余的,但就是不行! 这是
        //已知美孚< T>而不是富
        x.DoStuffImpl(本);
    }
}

然后:

 无效DoStuff(富富)
{
    foo.CallStuffImpl(本); //让它适当地派遣
}

I have the following scenario:

class Foo { }

class Foo<T> : Foo { }

And then two methods

void DoStuff(Foo foo) 
{
     DoStuffImpl(foo);
}

void DoStuffImpl(Foo foo) 
{ 
     Console.WriteLine("A");
}    
void DoStuffImpl<T>(Foo<T> foo) 
{ 
     Console.WriteLine("B");
} 

void Main() 
{
     DoStuff(new Foo<int>()); // prints A
}

(note, the code was written in the browser, but describes the situation I'm facing)

How can I get it to call the generic method, and print B?

Can this be done at all without reflection? I have some ideas on how it could be done with reflection, but I'm looking for a cleaner solution if one exists.

Note: I can't make DoStuff generic because this will be used with WCF and open generic types are not allowed.

解决方案

(I assume you already understand why this is happening. If not, read my overload resolution article and let me know if it's still unclear.)

If you're using C# 4 you could use dynamic typing:

void DoStuff(Foo foo) 
{
    dynamic d = foo;
    DoStuffImpl(d);
}

Note how this doesn't just have a dynamic parameter - the idea is that by restricting foo to be of type Foo or a subclass, we'll always have a valid DoStuffImpl to call... it's just that the best method will be determined at execution time, not compile time.

If you're stuck in pre-C# 4, you could potentially do it with double dispatch:

class Foo
{
    public virtual void CallStuffImpl(FooImplType x)
    {
        x.DoStuffImpl(this);
    }
}

class Foo<T> : Foo
{
    public override void CallStuffImpl(FooImplType x)
    {
        // Looks like it's redundant, but isn't! "this" is
        // known to be Foo<T> rather than Foo
        x.DoStuffImpl(this);
    }
}

Then:

void DoStuff(Foo foo) 
{
    foo.CallStuffImpl(this); // Let it dispatch appropriately
}

这篇关于通用重载解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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