现在的位置: 首页 > 综合 > 正文

C#转换运算符

2019年11月19日 ⁄ 综合 ⁄ 共 626字 ⁄ 字号 评论关闭
C# 允许程序员在类或结构上声明转换,以便类或结构与其他类或结构或者基本类型进行相互转换。
转换的定义方法类似于运算符,并根据它们所转换到的类型命名。

要转换的参数类型或转换结果的类型必须是(不能两者同时都是)包含类型。

class SampleClass
{
    public static explicit operator SampleClass(int i)
    {
        SampleClass temp = new SampleClass();
        // code to convert from int to SampleClass...

        return temp;
    }
}

转换运算符概述


转换运算符具有以下特点:

  • 声明为 implicit 的转换在需要时自动进行。

  • 声明为 explicit 的转换需要调用强制转换。

  • 所有转换都必须声明为 static

示例:

  

public class A
{
	public int MyProperty { get; set; }
}
public class B
{
	public Int32 MyProperty { get; set; }
	public static implicit operator B(A a)
	{
		B temp = new B();
		temp.MyProperty=a.MyProperty;
		return temp;
	}
}

A和B两个类默认并不能直接转换。但是B类做implicit声明后就可以直接隐式转换了:

A a = new A();
B b = a;

如果是使用的explicit作声明,则需要加括号强制转换。如果没有这样的声明,则会报转换异常。




抱歉!评论已关闭.