隐式和显式地将一个引用类型转换为另一个引用类型?

时间:2010-09-22 16:27:06

标签: c# .net

将一个引用类型隐式和显式转换为其他引用类型? 请举个例子来使答案更有效。

3 个答案:

答案 0 :(得分:6)

正如已经说过的那样,完全不清楚你实际要问的是什么......但很容易给出一些这样做的例子。

这是从stringXName的{​​{3}}:

XName name = "foo";

这在XName中声明,如下所示:

public static implicit operator XName (string expandedName)
{
    // Implementation
}

这是从XElementstring的{​​{3}}:

XElement element = new XElement(name, "some content");
string value = (string) element;

这在XElement中声明,如下所示:

public static explicit operator string (XElement element)
{
    // Implementation
}

现在,你真正想知道的是什么?

答案 1 :(得分:2)

这是一个定义和使用从一个类到另一个类的显式和隐式强制转换/转换的示例。

class Foo
{
    public static explicit operator Bar(Foo foo)
    {
        Bar bar = new Bar();
        bar.Name = foo.Name;
        return bar;
    }

    public string Name { get; set; }
}

class Bar
{
    public static implicit operator Foo(Bar bar)
    {
        Foo foo = new Foo();
        foo.Name = bar.Name;
        return foo;
    }

    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        Bar bar = (Bar)(new Foo() { Name = "Blah" }); // explicit cast and conversion
        Foo foo = bar; // implicit cast and conversion
    }
}

答案 2 :(得分:2)

隐式转换是指假设编译器或程序将为您转换值:

int myInt = 123;
object myObj = myInt;

显式转换是指在要转换的代码中指定“显式”的地方:

int myInt = 123;
object myObj = (object)myInt; //Here you specify to convert to an object
相关问题