IronPython重载类型的重载解析 [英] IronPython overload resolution on generic types

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

问题描述

我有一个C#类,带有重载的静态方法,如下所示:

I have a C# class with overloaded static methods like these:

// Added to the Simple class in Tutorial\Extend\csextend.cs
public static int Foo(IEnumerable<int> values)
{
    return 1;
}

public static int Foo(IEnumerable<string> values)
{
    return 2;
}

当我尝试从IronPython 2.6调用它们时出现错误.我正在传递包含字符串的python列表.

I get an error when I try to call these from IronPython 2.6. I am passing a python list that contains strings.

import clr
clr.AddReferenceToFile("csextend.dll")
import Simple

Simple.Foo(["alpha", "bravo", "charlie"])


TypeError: Multiple targets could match: Foo(IEnumerable[str]), Foo(IEnumerable[
int])

我的第一个问题是为什么这行不通?似乎过载解析应该可以解决此问题.这是IronPython中的错误吗?什么是最干净的解决方法.我可以重命名例程,以便它们不会彼此重载,但是随后,我让ironpython怪癖更改了C#类的设计.

My first question is why doesn't this work? It seems like overload resolution should work on this. Is this a bug in IronPython? What is the cleanest workaround. I could rename the routines so they don't overload each other, but then I am letting ironpython quirks alter the design of the C# class.

是否有一种干净的方法可以让python知道列表完全由一种类型组成,并且应该选择特定的重载?

Is there a clean way to give python a clue that the list is entirely composed of one type, and that it should pick a specific overload?

此问题

推荐答案

IronPython并没有真正的函数重载,只有一个具有所有功能的函数.通常,IronPython会自动执行此操作,但泛型类型会使事情复杂化.要消除使用哪个重载的歧义,请使用Overloads字典获取函数,并通过将签名中的类型作为键进行传递. (在撰写本文时,我正在使用IronPython 2.7,所以我不知道2.6版和2.7版之间是否有区别)

IronPython doesn't really have overloads of functions, just one single function with all the functionality. Normally IronPython would do this automatically but the generic types complicate things. To disambiguate which overload to use, get the function using the Overloads dictionary passing the types in the signature as the key. (I'm using IronPython 2.7 at the time of writing this so I don't know if there's a difference between version 2.6 and 2.7)

import System.Collections.Generic.IEnumerable as IEnumerable
Simple.Foo.Overloads[IEnumerable[str]](["alpha", "bravo", "charlie"])

如果函数中有更多参数,则将类型作为元组传入.

If there were more parameters in the functions, pass the types in as a tuple.

#public static int Foo(IEnumerable<string> values, string otherParam)
#{
#    return 3;
#}

Simple.Foo.Overloads[IEnumerable[str],str](["alpha", "bravo", "charlie"], "x")

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

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