gpt4 book ai didi

c# - c# 编译器是否会执行多个隐式转换以从一种类型转换为另一种类型?

转载 作者:太空狗 更新时间:2023-10-30 00:12:56 25 4
gpt4 key购买 nike

假设您有一个如下所示的类:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com