重学c#系列—— explicit、implicit与operator[三十四]

前言

我们都知道operator 可以对我们的操作符进行重写,那么explicit 和 implicit 就是对转换的重写。

正文

explicit 就是强制转换,然后implicit 就是隐式转换。

static void Main(string[] args)
{
	string a = string.Empty;
	ConsumeValue consumeValue = new ConsumeValue();
	consumeValue.Value = "测试数据";
	a = consumeValue;
	Console.WriteLine(a);
}

public struct ConsumeValue
{

	public string Value;

	public static implicit operator String(ConsumeValue consumeValue)
	{
		return consumeValue.Value;
	}
}

比如说,自己定义了一个结构体,然后让结构体可以和string之间相互转换。

那么你也可以写 string 转换为 ConsumeValue的。

static void Main(string[] args)
{
	string a = "测试数据";
	ConsumeValue consumeValue = a;
	Console.WriteLine(consumeValue.Value);
}

public struct ConsumeValue
{

	public string Value;

	public static implicit operator String(ConsumeValue consumeValue)
	{
		return consumeValue.Value;
	}

	public static implicit operator ConsumeValue(string value)
	{
		ConsumeValue consumeValue = new ConsumeValue();
		consumeValue.Value=value;

		return consumeValue;
	}
}

出了隐式转换,还可以强制转换。

static void Main(string[] args)
{
	string a = "测试数据";
	ConsumeValue consumeValue = (ConsumeValue)a;
	Console.WriteLine(consumeValue.Value);
}

public struct ConsumeValue
{

	public string Value;

	//public static implicit operator String(ConsumeValue consumeValue)
	//{
	//    return consumeValue.Value;
	//}

	//public static implicit operator ConsumeValue(string value)
	//{
	//    ConsumeValue consumeValue = new ConsumeValue();
	//    consumeValue.Value=value;

	//    return consumeValue;
	//}

	public static explicit operator String(ConsumeValue consumeValue)
	{
		return consumeValue.Value;
	}

	public static explicit operator ConsumeValue(string value)
	{
		ConsumeValue consumeValue = new ConsumeValue();
		consumeValue.Value = value;

		return consumeValue;
	}
}

强制转换就是需要在前面加上要转换的类型。

那么来看下这两者的原理。

隐式转换原理。

其实就是生成两个静态的方法。

然后调用。

所以隐式转换是安全的,就是我们调用方法一样。

那么看下强制转换的原理。

也是一样的。

这样我们就会存在一个疑问哈,那就是既然有隐式转换,自动帮我们验证,那么强制转换不是麻烦吗?

是的一般情况下,我们不用强制转换的,但是它有用武之地。

那就是传进来是一个object的时候。

static void Main(string[] args)
{
	object a = new ConsumeValue();
	ConsumeValue consumeValue = (ConsumeValue)a;
	Console.WriteLine(consumeValue.Value);
}

你不知道其类型的时候,比如有马 和 羊,还有车,他们没有继承关系的时候,你希望给他们进行代理抽象,那么你传进来的可能就是一个object,那么这个时候自然就是强制转换了。

写个伪代码

chouxiang:
  name
  // 强制转换的方法 yang ma che
yang:
  name
ma:
  name
che:
  name

方法:
string change(object a):
    var c = (chouxiang)a

大佬补充:

比如A(string str) A(ConsumerValue value), 调A("aaa")的时候可能调的不是自己想要的那个

现在还是尽量用is 和 as 吧,这样不会报错。

用强制还是隐式一般看场景,一般情况下还是用隐式,写起来比较舒服一些。

该系列继续更新。

posted @ 2023-03-18 18:34  敖毛毛  阅读(250)  评论(0编辑  收藏  举报