如何为将我的类转换为其他类型提供支持?例如,如果我有自己的管理 byte[]
的实现,并且我想让人们将我的类强制转换为 byte[]
,它只会返回私有(private)成员(member),我该怎么做?
让他们也将其转换为字符串是常见的做法,还是我应该覆盖 ToString()
(或两者)?
最佳答案
您需要覆盖转换运算符,使用 implicit
或 explicit
取决于您是希望用户必须强制转换还是希望它自动发生。通常,一个方向总是有效的,那就是你使用 implicit
的地方,而另一个方向有时会失败,那就是你使用 explicit
的地方。
语法是这样的:
public static implicit operator dbInt64(Byte x)
{ return new dbInt64(x); }
或
public static explicit operator Int64(dbInt64 x)
{
if (!x.defined) throw new DataValueNullException();
return x.iVal;
}
对于您的示例,从您的自定义类型说起(MyType
--> byte[]
将始终有效):
public static implicit operator byte[] (MyType x)
{
byte[] ba = // put code here to convert x into a byte[]
return ba;
}
或
public static explicit operator MyType(byte[] x)
{
if (!CanConvert) throw new DataValueNullException();
// Factory to convert byte[] x into MyType
return MyType.Factory(x);
}
关于c# - 我如何为我的类(class)提供定制类型转换支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1407689/