作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设您有一个如下所示的类:
public sealed class StringToInt {
private string _myString;
private StringToInt(string value)
{
_myString = value;
} public static implicit operator int(StringToInt obj)
{
return Convert.ToInt32(obj._myString);
}
public static implicit operator string(StringToInt obj)
{
return obj._myString;
}
public static implicit operator StringToInt(string obj)
{
return new StringToInt(obj);
}
public static implicit operator StringToInt(int obj)
{
return new StringToInt(obj.ToString());
}
}
你能不能写出如下代码:
MyClass.SomeMethodThatOnlyTakesAnInt(aString);
没有说明没有从字符串到 int 的隐式转换?
[是的,我可以自己测试,但我想我会把它放在那里,看看所有专家怎么说]
最佳答案
没有 C# 不会调用多个用户定义的隐式转换。来自 C# 规范第 6.4.3 节:
Evaluation of a user-defined conversion never involves more than one user-defined or lifted conversion operator. In other words, a conversion from type S to type T will never first execute a user-defined conversion from S to X and then execute a user-defined conversion from X to T.
关于c# - c# 编译器是否会执行多个隐式转换以从一种类型转换为另一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1611083/
我是一名优秀的程序员,十分优秀!