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

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

问题描述

我要如何铸造我的课到其他类型提供支持?举例来说,如果我有我自己的实现管理字节[] ,我希望让大家投我班一个字节[]的,这将只返回私有成员,我会怎么做呢?

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)?

推荐答案

您将需要重写转换操作符,即使用 明确 取决于你是否希望用户拥有投,或者你是否希望它自动地发生。一般情况下,一个方向会一直努力,这就是你使用,而另一个方向有时会失败,这就是你使用明确

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 - > 字节[] 将永久有效)

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天全站免登陆