我有一个这样的课:
public class Response<T>
{
public T Value { get; set; }
public static implicit operator T(Response<T> res)
{
return res.Value;
}
}
我通过三种方式使用隐式运算符:
public void Demo()
{
IList<int> good = test() as IList<int>; // This line is no problem
string good2 = test2(); // This line is no problem
IList<int> bad = test(); //Why this line doesn't work?
}
public Response<IList<int>> test()
{
return new Response<IList<int>>();
}
public Response<string> test2()
{
return new Response<string>();
}
为什么IList<int> bad = test()
不起作用,但显示“无法将类型'Response>'隐式转换为'System.Collections.Generic.IList'。存在显式转换(您是否缺少类型转换?)”
在有关转换运算符的部分中,我发现您的答案深藏在c#语言规范的内部:
如果T是接口类型,则将忽略用户定义的从S到T的隐式转换。
这意味着,如果您更改IList
为List
,则隐式转换应该可以正常工作:
public static void Main(string[] args)
{
IList<int> good = test() as IList<int>; // This line is no problem
string good2 = test2(); // This line is no problem
List<int> good3 = test3(); // This line works as well
//IList<int> bad = test(); // This fails...
}
static Response<IList<int>> test()
{
return new Response<IList<int>>();
}
static Response<List<int>> test3()
{
return new Response<List<int>>();
}
static Response<string> test2()
{
return new Response<string>();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句