Tuple.Create返回类型
鉴于
void foo(Tuple<object> t)
{
}
void bar()
{
foo(Tuple.Create("hello"));
}
c# 编译器返回
error CS1502: The best overloaded method match for 'foo(System.Tuple<object>)' has some invalid arguments
error CS1503: Argument 1: cannot convert from 'System.Tuple<string>' to 'System.Tuple<object>'
添加显式类型到 Tuple.Create 达不到其目的。如何说服编译器接受代码?
FWIW,我认为 C++ 没有这个问题: http://live.boost.org/doc/libs/1_33_1/libs/tuple/doc/tuple_users_guide.html#constructing_tuples
Given
void foo(Tuple<object> t)
{
}
void bar()
{
foo(Tuple.Create("hello"));
}
the c# compiler returns
error CS1502: The best overloaded method match for 'foo(System.Tuple<object>)' has some invalid arguments
error CS1503: Argument 1: cannot convert from 'System.Tuple<string>' to 'System.Tuple<object>'
Adding explicit types to Tuple.Create defeats its purpose. How can I convince the compiler to accept the code?
FWIW, I think C++ doesn't have this problem: http://live.boost.org/doc/libs/1_33_1/libs/tuple/doc/tuple_users_guide.html#constructing_tuples
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这与每天都会出现的通用类型协方差问题相同。根本不可能将
Foo
转换为Foo
,反之亦然。从 .NET 4 开始,它受到支持 - 但仅适用于接口和委托,并且通过声明Foo
来显式指定泛型类型参数作为变体。This is the same generic type covariance issue that comes up daily. It is simply not possible to convert
Foo<T>
toFoo<SubT>
or vice-versa. Starting with .NET 4, it is supported - but only for interfaces and delegates, and by explicitly specifying the generic type parameter as variant by declaring itFoo<out T1>
.您可以通过不使用
Tuple
如果您不想这样做,您只需需要在 Tuple.Create 方法中显式使用要对象的字符串。
考虑一下您是否可以拥有
Tuple
没有什么可以阻止您用该方法编写
,现在您只需将 1 放入仅允许字符串的元组中。诚然,这是一个极端情况,因为 Tuple 本质上是只读的,因此您需要一个 ref 参数,但这仍然是一个问题案例。
You can make the code compile by not using
Tuple<object>
but usingTuple<T>
If you don't want to do that, you simply will need to be explicit with the string to object in the Tuple.Create method.
Consider if you could have
Tuple<object>
and then pass in aTuple<string>
. What if your signature wasThere's nothing that stops you from writing in that method
And now you've just put a 1 in a tuple that only allows strings. Granted, it's a corner case as Tuple is inherently readonly so you need a
ref
parameter, but it's a problem case, nonetheless.您正在尝试将
Tuple
转换为Tuple
You are trying to turn a
Tuple<string>
into aTuple<object>
, which you cannot do - generic variance is only supported for interfaces and delegate. You need to explicitly specify the type arguments toTuple.Create
: