C# 显式和隐式类型转换有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1584293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between explicit and implicit type casts?
提问by Vijjendra
Can you please explain the difference between explicit
and implicit
type casts?
你能解释一下explicit
和implicit
类型转换之间的区别吗?
采纳答案by Marc Gravell
This is a little tricky because the "cast" syntax in C# actually does a range of differentthings (cast, primitive convert, bespoke convert, etc)
这有点棘手,因为 C# 中的“强制转换”语法实际上做了一系列不同的事情(强制转换、原始转换、定制转换等)
In an implicit cast, there is an obvious reference-preserving conversion between the two:
在隐式转换中,两者之间存在明显的引用保留转换:
List<int> l = new List<int>();
IList<int> il = l;
The compiler can prove that this is safe just from static analysis (List<int>
is always an IList<int>
)
编译器可以通过静态分析证明这是安全的(List<int>
总是一个IList<int>
)
With an explicit cast, either you are telling the compiler that you know more than it does- "please believe me, but check anyway":
使用显式转换,要么你告诉编译器你知道的比它多——“请相信我,但无论如何都要检查”:
List<int> l = new List<int>();
IList<int> il = l;
List<int> l2 = (List<int>)il;
Although this cast is possible, the compiler won't accept that allIList<int>
s are actually List<int>
- so we must tell it to let it by.
尽管这种转换是可能的,但编译器不会接受所有IList<int>
s 实际上都是List<int>
- 所以我们必须告诉它让它过去。
In an implicit primitive conversion (providedby the language spec), it is generally assumed that there is a safe, non-risky, non-lossy (caveat: see Jon's comment) conversion:
在隐式原始转换(由语言规范提供)中,通常假设存在安全、无风险、无损失(警告:请参阅 Jon 的评论)的转换:
int i = 1;
float f = i;
With an explicit primitive conversion, it is likely that the conversion couldlose data, or is non-obvious:
使用显式原始转换,转换很可能会丢失数据,或者不明显:
float f = 1;
int i = (int)f;
With bespoke operators, all bets are off, and you'd have to look at the documentation. It could be a reference-cast, or it could be anything. It may follow similar rules to primitive conversions (example: decimal
), or it could do anything randomly:
对于定制的运营商,所有的赌注都没有了,您必须查看文档。它可以是引用转换,也可以是任何东西。它可能遵循与原始转换类似的规则(例如:)decimal
,或者它可以随机执行任何操作:
XNamespace ns = "http://abc/def"; // implicit
XAttribute attrib = GetAttrib();
int i = (int)attrib; // explicit (extracts text from attrib value and
// parses to an int)
Both of these run custom code that is context-specific.
这两者都运行特定于上下文的自定义代码。
回答by Cameron MacFarland
int i = 2;
float a = i; // Implicit
float b = (float)i; // Explicit
回答by AndreyAkinshin
回答by Reshure
Explicit cast:
显式转换:
int x = 0;
float y = 3.8f;
x += (int) y; //Explicit cast.
This tells the compiler that the cast was intentional and that you know that the fractional part will go lost. The compiler won't complain.
这告诉编译器强制转换是有意的,并且您知道小数部分将丢失。编译器不会抱怨。
Implicit cast:
隐式转换:
int x = 0;
float y = 3.8f;
x += y; //Implicit cast
The compiler will complain because the fractional part will be lost when converting float to int.
编译器会抱怨,因为在将 float 转换为 int 时小数部分会丢失。
回答by Eric Lippert
What's the difference between the President of the United States and the President of Canada?
美国总统和加拿大总统有什么区别?
Since there is no President of Canada, it's hard to answer the question. The right thing to do is to push back and ask for clarification of the question. By "the President of Canada", does the questioner mean the Queen (ceremonial head of state), the Governor General (who can veto bills) or the Prime Minister (who effectively acts as the executive), or something else? Hard to say without clarification.
由于没有加拿大总统,这个问题很难回答。正确的做法是反击并要求澄清问题。提问者所说的“加拿大总统”是指女王(正式的国家元首)、总督(可以否决法案)还是总理(实际上是执行官),还是其他什么?没有澄清就很难说。
And even with clarification, it's a vague question. What differences do you want to know about?
即使澄清了,这也是一个模糊的问题。您想了解哪些差异?
Since there is no such thing as an "implicit cast" in C# it is hard to answer your question. In C#, casting is an operator. So I'll push back on it.
由于 C# 中没有“隐式强制转换”这样的东西,因此很难回答您的问题。在 C# 中,强制转换是一个运算符。所以我会反击它。
Did you mean to ask "what's the difference between an explicit conversion and an implicit conversion?" Or did you mean to ask about the semantics of the cast operator? Or the difference between the cast operator and other type conversion operators? Or situations in which cast operators can be "implicitly" inserted into your code by the compiler? (For example, the foreach loop and the += operator can both implicitly insert an invisible cast.)
您的意思是问“显式转换和隐式转换有什么区别?” 或者您的意思是询问强制转换运算符的语义?或者cast操作符和其他类型转换操作符的区别?或者编译器可以“隐式”插入到您的代码中的情况?(例如,foreach 循环和 += 运算符都可以隐式插入一个不可见的强制转换。)
Can you clarify the question? What two things are you asking for comparison of, and what sorts of differences are you interested in?
你能澄清这个问题吗?您要求比较哪两件事,以及您对哪些差异感兴趣?
You might consider reading the "Conversions" chapter of the C# specification. Odds are good that any question you have about conversions are answered there.
您可以考虑阅读 C# 规范的“转换”一章。很有可能您对转换的任何问题都会在那里得到解答。
回答by Shaitender Singh
A simple search will give lots of informations in the net.
difference between implicit and explicit type
简单的搜索将在网络中提供大量信息。
隐式和显式类型的区别
回答by Vivek Kumar
Explicit Conversions
显式转换
If a conversion cannot be made without a risk of losing information then it is an explicit conversion.
如果不能在没有丢失信息的风险的情况下进行转换,则它是显式转换。
For example -
例如 -
class ExplicitConversions
{
static void Main()
{
int x;
double y = 6358.057;
// Cast double to int.
x = (int)y;
System.Console.WriteLine(x);
}
}
Implicit Conversions
隐式转换
If a conversion can be made without a risk of losing information then it is an implicit conversion. No special syntax is required because the conversion is type safe and no data is lost.
如果可以在没有丢失信息风险的情况下进行转换,那么它就是隐式转换。不需要特殊语法,因为转换是类型安全的并且不会丢失数据。
For example -
例如 -
class ImplicitConversions
{
static void Main()
{
int x = 6714;
double y;
// Cast int to double.
y = x;
System.Console.WriteLine(y);
}
}
回答by Bhalchandra K
Explicit from MSDN-
来自MSDN 的明确-
If a conversion operation can cause exceptions or lose information, you should mark it explicit. This prevents the compiler from silently invoking the conversion operation with possibly unforeseen consequences.
如果转换操作可能导致异常或丢失信息,则应将其标记为显式。这可以防止编译器以静默方式调用转换操作,并可能产生不可预见的后果。
Implicit from MSDN-
来自MSDN 的隐式-
if the conversion is guaranteed not to cause a loss of data
如果保证转换不会导致数据丢失