将Python数组转换为C#并返回值

时间:2018-11-01 18:53:18

标签: c# python arrays grasshopper rhino3d

我正在将Python脚本转换为C#,并且需要一些帮助。我只是真的没有任何Python经验。这些类型的数组对我来说是全新的。

倒数第二行var posVec = dSorted[0][1];和最后一行return posVec;都很麻烦。

var posVec的实际变量类型是什么?

我还试图返回posVec,它应该是Vector3d,但出现此错误:

  

不能将类型'double'隐式转换为'Rhino.Geometry.Vector3d'

我在做什么错? 谢谢!

Python:

posVec = dSorted[0][1]
return posVec

完整的Python方法:

def getDirection(self):
    #find a new vector that is at a 90 degree angle

    #define dictionary
    d = {}
    #create an list of possible 90 degree vectors
    arrPts = [(1,0,0), (-1,0,0), (0,1,0), (0,-1,0)]
    vec = self.vec
    vec = rs.VectorUnitize(vec)

    #find the distance between the self vec
    #position and one of the 4 90 degree vectors
    #create a dictionary that matches the distance with the 90 degree vector
    for i in range(4):
        dist = rs.Distance(vec, arrPts[i])
        d[dist] = arrPts[i]
    #sort the dictionary.  This function converts it to an array
    #sort by the distances, "value"/item 0
    dSorted = sorted(d.items(), key=lambda value: value[0])

    #select the second item in the array which is one of the 90 degree vectors
    posVec = dSorted[0][1]
    return posVec

到目前为止,我已经重写了完整的C#方法:

    // find a new vector that is at a 90 degree angle
    public Vector3d GetDirection()
    {
        // define dictionary
        Dictionary<double, Vector3d> d = new Dictionary<double, Vector3d>();

        Vector3d[] arrPts = new Vector3d[] {
            new Vector3d(1, 0, 0),
            new Vector3d(-1, 0, 0),
            new Vector3d(0, 1, 0),
            new Vector3d(0, -1, 0),
            new Vector3d(0, 0, 1),
            new Vector3d(0, 0, -1) };

        _vec = Vec;
        _vec.Unitize();

        // find the distance between the self vec position and one of the 6 90 degree vectors
        // create a dictionary that matches the distance with the 90 degree vector

        for (int i = 0; i < arrPts.Length; i++)
        {
            double dist = Math.Sqrt(
                ((_vec.X - arrPts[i].X) * (_vec.X - arrPts[i].X)) +
                ((_vec.Y - arrPts[i].Y) * (_vec.Y - arrPts[i].Y)) +
                ((_vec.Z - arrPts[i].Z) * (_vec.Z - arrPts[i].Z)));

            d.Add(dist, arrPts[i]);
        }

        Vector3d[] dSorted = d.Values.ToArray();
        var posVec = dSorted[0][1];
        return posVec;
    }

1 个答案:

答案 0 :(得分:0)

我参加晚会很晚,但是无论如何,如果将来为某人服务...

您正在根据自己的Vector3d(dSorted)的值创建一个dictionary(d)的数组,但是您尝试使用{{1}将其强制转换为var posVec的{​​{1}} }}。这是锯齿状数组的表示法,但是您声明Vector3ddSorted[0][1]的数组。

因此,只需使用dSorted即可访问其项之一。