c# - 我如何为我的类(class)提供定制类型转换支持?

标签 c# casting

如何为将我的类转换为其他类型提供支持?例如,如果我有自己的管理 byte[] 的实现,并且我想让人们将我的类强制转换为 byte[],它只会返回私有(private)成员(member),我该怎么做?

让他们也将其转换为字符串是常见的做法,还是我应该覆盖 ToString()(或两者)?

最佳答案

您需要覆盖转换运算符,使用 implicitexplicit取决于您是希望用户必须强制转换还是希望它自动发生。通常,一个方向总是有效的,那就是你使用 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/

相关文章:

arrays - 暂时将 [u8] 转化为 [u16]

c++ - C++运算符中的隐式类型转换规则

时间:2019-03-17 标签:c#EventlogFullorNot

c# - 什么时候使用 try/catch block ?

c# - 从非托管 dll 文件调用托管 dll(注入(inject)正在运行的进程)

c# - 如何列出我的解决方案中的所有 DLL 并获取其版本?

delphi - 将 TArray<X> 类型转换为 X 数组是否安全?

c# - DEVEXPRESS - xtrareport - 分页符

c++ - 转换指针以重用缓冲区

java - 泛型的协方差转换