c#参数通过类字段传入ref

c#参数通过类字段传入ref,c#,class,parameters,field,ref,C#,Class,Parameters,Field,Ref,我想交换ConvexHull类中的字段,就像交换(点[0],点[1]) 我该怎么办 public class ConvexHull { List<Point> points; public void run () { Point.swap ( ref points[ 0 ], ref points[ 1 ] ); //Error!! } } public class Point { private double x, y;

我想交换ConvexHull类中的字段,就像交换(点[0],点[1])

我该怎么办

public class ConvexHull
{
    List<Point> points;

    public void run ()
    {
        Point.swap ( ref points[ 0 ], ref points[ 1 ] );  //Error!!
    }
}

public class Point
{
    private double x, y;

    Point () { x = y = 0; }
    public static void swap(ref Point a, ref Point b) {
        Point c = a;
        a = b;
        b = c;
    }
}
公共类convxhull
{
列出要点;
公开作废运行()
{
Point.swap(参考点[0],参考点[1]);//错误!!
}
}
公共课点
{
私人双x,y;
点(){x=y=0;}
公共静态无效交换(参考点a、参考点b){
c点=a点;
a=b;
b=c;
}
}

列表的元素编制索引时
实际上是在访问
这个
索引器,它是一种属性(即具有getter和setter方法)。只能将变量作为
ref
out
传递,不能传递属性

在您的场景中,可能您想要更像这样的东西:

public class ConvexHull
{
    List<Point> points;

    public void run ()
    {
        swap(0, 1);  //No error!!
    }

    private void swap(int i, int j)
    {
        Point point = points[i];

        points[i] = points[j];
        points[j] = point;
    }
}
public class ConvexHull
{
    List<Point> points;

    public void run ()
    {
        points.SwapElements(0, 1);
    }
}

static class Extensions
{
    public static void SwapElements<T>(this List<T> list, int index1, int index2)
    {
        T t = list[index1];

        list[index1] = list[index2];
        list[index2] = t;
    }
}
公共类convxhull
{
列出要点;
公开作废运行()
{
交换(0,1);//没有错误!!
}
私有无效交换(int i,int j)
{
点=点[i];
点[i]=点[j];
点[j]=点;
}
}
更通用的解决方案可能如下所示:

public class ConvexHull
{
    List<Point> points;

    public void run ()
    {
        swap(0, 1);  //No error!!
    }

    private void swap(int i, int j)
    {
        Point point = points[i];

        points[i] = points[j];
        points[j] = point;
    }
}
public class ConvexHull
{
    List<Point> points;

    public void run ()
    {
        points.SwapElements(0, 1);
    }
}

static class Extensions
{
    public static void SwapElements<T>(this List<T> list, int index1, int index2)
    {
        T t = list[index1];

        list[index1] = list[index2];
        list[index2] = t;
    }
}
公共类convxhull
{
列出要点;
公开作废运行()
{
点。Swaplements(0,1);
}
}
静态类扩展
{
公共静态无效交换(此列表,int index1,int index2)
{
T=列表[index1];
列表[index1]=列表[index2];
列表[index2]=t;
}
}

在任何一种情况下,正确的方法都是为实际交换值的代码提供对
列表
对象本身的访问权,以便它可以访问索引器属性来完成交换。

几乎放弃了所有这些。您不能通过引用传递属性或列出对象。我注意到最初没有填充这些点。填充点列表,然后调用ConvexHull类中的函数来交换点(int point1idx,int point2idx),并在那里编写代码来进行交换


在Point类上,暴露X和Y,并从此处删除交换例程,因为它永远不会工作

您得到的错误是什么?让Point类进行交换似乎是一种奇怪的设计。为什么不在ConvexHull类中使用swap方法并传递要交换的两个位置的int索引值呢?用户无法读取或写入
点的
x
y
值也似乎很奇怪。我的意思是,什么是
?代码将生成的错误是
参数未被归类为变量
编译错误。哇。。。我非常感激。