请给我 C# 中隐式和显式类型转换的例子 [英] Please give me example of implicit and explicit type conversion in C#
问题描述
谁能给我在现实生活中隐式类型转换的例子.我知道隐式类型转换意味着从派生类到基类的转换,但我不知道如何在 C# 中进行编码.我不想在 2 行中定义它.我想定义一个完整的程序来显示 c# 中的隐式和显式类型转换.请帮帮我.
can any one give me implicit type conversion example in real life. I know implicit type conversion means conversion from derived to base class but i don't know how to show in coding in c#. I don't want to define it in 2 lines. I want to define a full program to show implicit and explicit type conversion in c#. Please help me.
问候
推荐答案
不,隐式类型转换只是意味着不需要在代码中显式的类型转换.
No, implicit type conversion just means a type conversion which doesn't need to be explicit in the code.
LINQ to XML 提供了很好的例子:
LINQ to XML provides good examples:
// Implicit conversion from string to XNamespace
XNamespace ns = "http://url.com";
XElement element = new XElement("foo", "bar");
// Explicit conversion of XElement to string
string value = (string) element;
这就是它们使用的方式 - 您可以使用 MSDN 中显示的代码类型创建自己的显式或隐式转换运算符(明确,隐式).
So that's how they're used - and you create your own explicit or implicit conversion operators using the kind of code shown in MSDN (explicit, implicit).
简短、完整但毫无意义的例子:
Short, complete, but pointless example:
class Foo
{
private readonly int value;
private Foo(int value)
{
this.value = value;
}
public static implicit operator Foo(int value)
{
return new Foo(value);
}
public static explicit operator int(Foo foo)
{
if (foo == null)
{
throw new ArgumentException("foo");
}
return foo.value;
}
}
class Test
{
static void Main(string[] args)
{
int x = 10;
Foo foo = x;
int y = (int) foo;
}
}
这篇关于请给我 C# 中隐式和显式类型转换的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!