是否可以将对象拆分为多个值类型?

时间:2015-01-20 13:55:17

标签: c#

我已经通过C#阅读了CLR:

  

取消装箱实际上只是获取指针的操作   对象中包含的原始值类型(数据字段)。

这意味着如果对象中包含多个值类型,则可以使用以下语法将其取消装箱:

int a= (int) o; //assigns a to 10
char b= (char) o; // assigns b to 'b'

如何实现支持多个拆箱的对象?

3 个答案:

答案 0 :(得分:2)

盒装值只能是单一类型的盒装形式 - 如果您致电o.GetType(),您将会发现它是什么。

一般情况下,你只能拆箱到完全相同的类型,但有一些皱纹:

  • 您可以将枚举值取消装入其基础整数类型,反之亦然
  • 没有盒装可空值类型 - 装箱将导致非可空类型的盒装形式或空引用。您可以取消可以为空的值类型,结果将是空值(如果原始引用是空引用)或包含未装箱的非可空值的非空值,如果你明白我的意思了。

例如:

object o = 10;
FileMode mode = (FileMode) o; // Valid conversion to enum

int? n = (int?) o; // n has a value of 10
n = null;
o = n; // o's value is a null reference
n = (int?) o; // n's value is the null int? value

答案 1 :(得分:1)

你在谈论铸造吗?在.NET中,如果你有一个盒装类型,它有一个特定的类型,你只能将它转换为实际值类型为unbox:

object o=10;               // o is a boxed int with value 10
var a=(int)o;              // works
//var b=(byte)o;           // ERROR, this is not what's contained in it
var b=(byte)(int)o;        // works, you get the int out then cast it to byte
var b=Convert.ToByte(o);   // also works, using IConvertible

然而,泛型的主要目的(最初至少)是因为涉及的性能成本而完全避免装箱值类型。您可以将object的大多数实例更改为通用值并保留类型,当您使用它们时,您将立即拥有正确的值类型。

答案 2 :(得分:0)

如果您有一个自定义对象,例如int或字符串,则可以使用explicit conversion operators执行此操作。

实施例

public class CustomObject
{
    int Number;
    string Text;

    public CustomObject(int number, string text)  //constructor
    {
        Number = number;
        Text = text;
    }

    public static explicit operator int(CustomObject o)
    {
        return o.Number;
    }

    public static explicit operator string(CustomObject o)
    {
        return o.Text;
    }
}

Fiddle example

相关问题