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

问题描述

如何支持将我的类转换为其他类型?例如,如果我有自己管理 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
    return MyType.Factory(x);
}

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

08-31 06:21