简体   繁体   English

将特定类型对象分配到通用数组中

[英]Assigning specific type object into an generic array

I have a generic type called Vector<T> , I created it as so, cause the T might be float or Complex : 我有一个名为Vector<T>的泛型类型,我是这样创建的,因为T可能是floatComplex

public class Vector<T>
    {
        #region Properties
        public ulong Length
        {
            get
            {
                return _length;
            }
        }
        public VectorType VectorType
        {
            get
            {
                return _vectorType;
            }
        }

        #endregion

        #region Indexers
        public T this[ulong index]
        {
            get
            {
                return _data[index];
            }
            set
            {
                _data[index] = value;
            }
        }

        #endregion

        #region Constructors

        public Vector(VectorType vectorType, T[] data)
        {
            if (!((data is float[]) || (data is Complex[])))
            {
                throw new InvalidDataException("Data must be array of float or array of Complex");
            }
            _data = new T[_length = (ulong)data.Length];
            for (ulong i = 0; i < _length; i++)
            {
                _data[i] = data[i];
            }
            _vectorType = vectorType;
        }


        public Vector(VectorType vectorType, Vector<T> vector)
        {
            _data = new T[_length = vector.Length];
            for (ulong i = 0; i < _length; i++)
            {
                _data[i] = vector[i];
            }
            _vectorType = vectorType;
        }

        #endregion

        #region Methods

            //Unity Matrix, this vector has 1/N everywhere
            public static Vector<float> e(VectorType vectorType, ulong length)
            {
                var data = new float[length];
                for (ulong i = 0; i < length; i++)
                {
                    data[i] = (float)1 / length;
                }
                var vectorE = new Vector<float>(vectorType, data); 
                return vectorE;
            }

            public float Sum()
            {
                float sum = 0;
                if (_data is float[])
                {
                    sum = (_data as float[]).Sum();
                }
                else
                {
                    if (_data is Complex[])
                    {
                        for (ulong i = 0; i < _length; i++)
                        {
                            sum += (float)
                                Math.Sqrt(Math.Pow((_data[i] as Complex?).Value.Real, 2) +
                                          Math.Pow((_data[i] as Complex?).Value.Imaginary, 2));
                        }
                    }
                }
                return sum;
            }

            public bool CheckIfSochasitc()
            {
                return Math.Abs(Sum() - 1) < float.Epsilon;
            }

            public void Normalize()
            {
                var sum = Sum();

                if (_data is float[])
                {
                    for (ulong i = 0; i < _length; i++)
                    {
                        float x = ((float) _data[i])/sum;
                        _data[i] =  (T)x;
                    }
                }

            }

        #endregion

        #region Operators
        //I omitted the code inhere to avoid overload
        #endregion

        #region Fields

            private  ulong _length;
            private readonly VectorType _vectorType;
            private T[] _data;

        #endregion
    }

    public enum VectorType
    {
        Row,Column        
    }

My problem is that I have a generic array (if I can call it so) : 我的问题是我有一个通用数组(如果我可以调用它):

private T[] _data;

And I have the Normalize() method: 我有Normalize()方法:

public void Normalize()
          {
             var sum = Sum();
             if (_data is float[])
             {
                for (ulong i = 0; i < _length; i++)
                {
                    //Here is the problem
                    _data[i] =  ((_data[i] as float?) / sum);
                }
             }
          }

This doesn't work saying can't cast float to T tried to search but couldn't find helpful aide, any clarification I'd be thankful. 这不起作用说can't cast float to T试图搜索但找不到有用的助手,任何澄清我都要感恩。

Update : 更新:

The Sum() method always returns a float Sum()方法总是返回一个float

It's not clear why you're converting to float? 目前尚不清楚为什么要转换为float? at all (or why you're using ulong as the index variable type...) but you just need to cast the result back to T - otherwise you can't assign it back into an array of type T[] . 完全(或者为什么你使用ulong作为索引变量类型...)但你只需要将结果转换回T - 否则你不能将它分配回T[]类型的数组。 Additionally, you need to cast to object (in order to convert back to T : 此外,您需要转换为object (为了转换回T

float x = ((float) (object) data[i]) / sum;
data[i] = (T) (object) x;

You can use float? 可以使用float? for the first line, with as , to avoid boxing - but then you need to get the non-nullable value: 对于第一行,使用as ,以避免装箱 - 但是你需要获得不可为空的值:

float x = (data[i] as float?).Value / sum;

Both are pretty ugly :( 两者都很难看:(

As noted in comments though, this sort of thing is usually an indication of the design not really being properly generic at all. 正如评论中所指出的那样,这种事情通常表明设计根本没有真正的通用性。 We don't know what type Sum() returns, but you should consider just how "general" your type is to start with. 我们不知道Sum()返回什么类型,但你应该考虑你的类型开始时的“一般”。

May be you can try this 也许你可以试试这个

if (typeof(_data) == float[])
             {
                for (ulong i = 0; i < _length; i++)
                {
                    _data[i] =  ((_data[i] as float?) / sum);
                }
             }

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

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