简体   繁体   English

如何存储混合数组数据?

[英]How To Store Mixed Array Data?

Let's say I have an array I need to store string values as well as double values. 假设我有一个数组,我需要存储字符串值以及双值。 I know I can store the doubles as strings, and just deal with the conversions, but is it possible to use an array with two data types? 我知道我可以将双打存储为字符串,只处理转换,但是可以使用具有两种数据类型的数组吗?

You may use object[] and do some type checking. 您可以使用object[]并进行一些类型检查。 You will get some boxing/unboxing when accessing the doubles, but that will be faster than double.Parse() anyway. 在访问双打时你会得到一些装箱/拆箱,但这比double.Parse()要快。

An alternative is to create a class with both types and a marker: 另一种方法是创建一个包含两种类型和标记的类:

class StringOrDouble
{
    private double d;
    private string s;
    private bool isString;

    StringOrDouble(double d)
    {
        this.d = d;
        isString = false;
    }

    StringOrDouble(string s)
    {
        this.s = s;
        isString = true;
    }

    double D
    {
        get
        {
            if (isString)
                throw new InvalidOperationException("this is a string");
            return d;
        }
    }

    string S
    {
        get
        {
            if (!isString)
                throw new InvalidOperationException("this is a double");
            return s;
        }
    }
    bool IsString { get { return isString; } }
}

and then create an array of StringOrDouble. 然后创建一个StringOrDouble数组。 This will save you from some typechecking and boxing, but will have a larger memory overhead. 这将节省你的一些类型检查和拳击,但会有更大的内存开销。

sure use: 确定使用:

object[], ArrayList, or List<Object>;

You'll have to cast, and probably pay a boxing penalty for the doubles, but they will allow you to store two different types. 你必须施放,并可能为双打支付拳击罚金,但他们将允许你存储两种不同的类型。

Not the most efficient usage, but how about for flexibility: 不是最有效的用法,但灵活性如何:

var a = new object[] {1,2,3,"paul",5.5}

or even 甚至

var a = new object[] {1,2,3,"paul",5.5, new List<string>() {"apple","banana","pear"}  }

object[] and ArrayList are two decent options; object[]ArrayList是两个不错的选择; it depends on whether you need a traditional fixed-length array or a vector (variable-length array). 这取决于您是需要传统的固定长度数组还是矢量(可变长度数组)。 Further, I would "wrap" one of these in a custom class that did some type-checking, if strings and doubles are the ONLY things you can deal with, and you need to be able to get them back out as strings and doubles. 此外,我将其中一个“包装”在一个自定义类中进行一些类型检查,如果字符串和双精度是你可以处理的唯一的东西,你需要能够将它们作为字符串和双精度返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM