将一个引用类型隐式和显式转换为其他引用类型? 请举个例子来使答案更有效。
答案 0 :(得分:6)
正如已经说过的那样,完全不清楚你实际要问的是什么......但很容易给出一些这样做的例子。
这是从string
到XName
的{{3}}:
XName name = "foo";
这在XName
中声明,如下所示:
public static implicit operator XName (string expandedName)
{
// Implementation
}
这是从XElement
到string
的{{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