2012-01-04 59 views
9

我想使用c#Point类型作为引用类型(它是一个结构体)。我想到了一个类CPoint,其中将包含一个Point成员。有什么办法可以提高Point的成员以充当Cpoint的成员。我试图避免C# - 值类型的引用包装

cpoint.point.X; 
cpoint.point.Y; 

我愿做

cpoint.X; 
cpoint.Y; 

,以及保持所有的转换,运营商,Empty
可以这样很容易做到?

+0

你为什么要/需要这样一个包装? – Xint0 2012-01-04 22:37:57

+0

@ Xint0就像我说的,用它作为参考类型。 – baruch 2012-01-04 22:42:18

+2

@barunch:在这之前,请考虑**有一个原因**为什么这种简单的类型被定义为'structs'。其中之一是,'struct'分配速度非常快,在绘图方法中使用'Point'结构,分配和释放速度至关重要。 – Tigran 2012-01-04 22:54:58

回答

4

如果你需要它像一个参考类型,然后使用ref关键字。它可以让你通过参考。有了这个,你将获得它作为一个结构所带来的所有性能优势,以及当你期望它像一个参考时那样具体地知道。您也可以使用out关键字通过引用返回参数。

如果你需要它能够代表null,则使用Nullable<T>

如果你只是想访问就像foo.MyPoint.X然后宣布它作为一个领域,像这样:

class Foo { 
    public Point MyPoint; 
} 
+1

我一直在c#编程,因为它是第一次创建,并且从来不知道你可以这样做(使用“参考“与值类型)!但是,这有其局限性:不能将该“引用”存储为集合的一个元素。 – ToolmakerSteve 2017-02-03 16:58:16

5

我认为唯一的办法就是重新编写和直通所有属性,运算符和方法,就像这样:

public class PointReference { 
    private Point point; 

    public int X { get { return point.X; } set { point.X = value; } } 
} 

(类名称的改动意; CPoint不是很表情)

+1

编辑我的答案不是唯一的方法,而是一种方式 – recursive 2012-01-04 22:41:38

+0

你知道另一种方式吗? – Yogu 2012-01-04 22:44:14

+5

当然,不要使用'Point',而是完全自己实现它。 – recursive 2012-01-04 22:44:51

8

这样的事情?

public class CPoint { 
    private Point _point = new Point(0,0); 
    public double X { get { return _point.X; } set { _point.X = value; } } 
    public double Y { get { return _point.Y; } set { _point.Y = value; } } 
    public CPoint() { } 
    public CPoint(Point p) { _point = p; } 
    public static implicit operator CPoint(Point p) { return new CPoint(p); } 
    public static implicit operator Point(CPoint cp) { return cp._point; } 
} 

编辑:如果你想有这个自动转换/从点,实现隐式转换按照上述。注意我没有测试过这些,但它们应该可以工作。更多的信息在这里:http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx

+0

是的,除了它为每个操作符和转换都做了这个工作非常烦人...... – baruch 2012-01-04 22:43:24

+0

查看已添加的隐式转换 – 2012-01-04 22:56:17