【发布时间】:2026-01-27 07:15:01
【问题描述】:
【问题讨论】:
【问题讨论】:
首先,这是
的副本What is the difference between casting and conversion?
灵感来自
What is the (type) in (type)objectname.var
我会先阅读这些内容,然后再回到这个简短的摘要。
请参阅规范第 6 章的第一段,其中指出:
转换使表达式能够 被视为特定的 类型。转换可能会导致 给定类型的表达式为 被视为具有不同的类型,或 它可能会导致没有 a 的表达式 type 获取类型。转换可以 隐式或显式,而这 确定显式转换是否是 必需的。例如,转换 从 int 类型到 long 类型是 隐式的,所以 int 类型的表达式 可以隐式地被视为类型 长。相反的转换,从 键入 long 以键入 int,是显式的并且 所以需要一个明确的演员表。
我们从中学到了什么?
转换是对两个操作数的语义操作:表达式和类型。
语义分析确定的确切操作决定了实际值在运行时如何转换。
cast 是 (type)expression 形式的 C# 语言的 句法元素,它显式地从类型的表达式。
这些只是您可以在 C# 中进行的一些隐式转换:
short aa = 123; // numeric constant conversion from int to short
int bb = aa; // numeric conversion from short to int
int? cc = null; // nullable conversion from null literal to nullable int.
object dd = "hello"; // implicit reference conversion from string to object
IEnumerable<Giraffe> ee = new Giraffe[] { new Giraffe() } ;
// implicit reference conversion from array to sequence
IEnumerable<Animal> ff = ee;
// implicit reference conversion involving array covariance
ff = null; // implicit reference conversion from null literal to sequence
bb = 456; // implicit identity conversion from int to int
dd = bb; // implicit boxing conversion from int to object
Func<int, int> gg = x=>x+x;
// anonymous function to delegate type conversion
显式转换通常但并非总是需要强制转换:
aa = (short)bb; // explicit numeric conversion
string hh = (string)dd; //explicit reference conversion
等等。
合法使用强制转换进行隐式转换,但通常没有必要。
清楚吗?关键是转换是一种语义操作,它会导致运行时的动作,而强制转换是告诉编译器分析转换的句法元素使用显式转换分析规则。
如果您对转换逻辑的主题感兴趣,那么您可能会对我关于该主题的文章感兴趣,这些文章在这里:
http://blogs.msdn.com/b/ericlippert/archive/tags/conversions/
【讨论】:
转换 = 实际上将对象转换为不同类的实例 例如:
int i = 3;
string str = i.ToString();
将整数转换为字符串
强制转换 = 强制对象的类型,因为你比编译器知道的更多 例如:
object obj = 3;
int i = (int)obj;
【讨论】:
Here 是一个很好的线程,其中包含一些示例和对您问题的回答。
【讨论】: