请给我一个C#中隐式和显式类型转换的例子

3 c# type-conversion implicit-conversion

任何人都可以在现实生活中给我隐式类型转换的例子.我知道隐式类型转换意味着从派生到基类的转换,但我不知道如何在c#中进行编码.我不想在2行中定义它.我想定义一个完整的程序来显示c#中的隐式和显式类型转换.请帮我.

问候

Jon*_*eet 12

不,隐式类型转换只是意味着一种类型转换,它不需要在代码中显式化.

LINQ to XML提供了很好的例子:

// 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;
Run Code Online (Sandbox Code Playgroud)

这就是它们的使用方式 - 您可以使用MSDN中显示的代码(显式,隐式)创建自己的显式或隐式转换运算符.

简短,完整,但毫无意义的例子:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)