如何为我的类提供自定义转换支持? [英] How do I provide custom cast support for my class?

查看:94
本文介绍了如何为我的类提供自定义转换支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何提供支援将我的课程转换为其他类型?例如,如果我有自己的实现管理一个 byte [] ,我想让人们把我的类转换为 byte [] ,这将只是返回私有成员,我将如何做到这一点?

How do I provide support for casting my class to other types? For example, if I have my own implementation of managing a byte[], and I want to let people cast my class to a byte[], which will just return the private member, how would I do this?

这是常见的做法是让他们也把这个字符串,或者我应该覆盖 ToString()(或两者)?

Is it common practice to let them also cast this to a string, or should I just override ToString() (or both)?

推荐答案

您需要使用 隐含 显式 ,具体取决于您是否希望用户投放它,还是希望自动发生。一般来说,一个方向总是工作的,那是你使用 implicit 的地方,而另一个方向有时可能会失败,这是你使用 explicit

You would need to override the conversion operator, using either implicit or explicit depending on whether you want users to have to cast it or whether you want it to happen automagically. Generally, one direction will always work, that's where you use implicit, and the other direction can sometimes fail, that's where you use 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 [] 将始终工作):

For your example, say from your custom Type (MyType --> byte[] will always work):

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
    MyType mt = MyType.Factory(x);
    return mt;
}

这篇关于如何为我的类提供自定义转换支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆