我想使用c#Point
類型作爲引用類型(它是一個結構體)。我想到了一個類CPoint
,其中將包含一個Point
成員。有什麼辦法可以提高Point
的成員以充當Cpoint
的成員。我試圖避免C# - 值類型的引用包裝
cpoint.point.X;
cpoint.point.Y;
我願做
cpoint.X;
cpoint.Y;
,以及保持所有的轉換,運營商,Empty
等
可以這樣很容易做到?
我想使用c#Point
類型作爲引用類型(它是一個結構體)。我想到了一個類CPoint
,其中將包含一個Point
成員。有什麼辦法可以提高Point
的成員以充當Cpoint
的成員。我試圖避免C# - 值類型的引用包裝
cpoint.point.X;
cpoint.point.Y;
我願做
cpoint.X;
cpoint.Y;
,以及保持所有的轉換,運營商,Empty
等
可以這樣很容易做到?
如果你需要它像一個參考類型,然後使用ref關鍵字。它可以讓你通過參考。有了這個,你將獲得它作爲一個結構所帶來的所有性能優勢,以及當你期望它像一個參考時那樣具體地知道。您也可以使用out關鍵字通過引用返回參數。
如果你需要它能夠代表null,則使用Nullable<T>
如果你只是想訪問就像foo.MyPoint.X
然後宣佈它作爲一個領域,像這樣:
class Foo {
public Point MyPoint;
}
我一直在c#編程,因爲它是第一次創建,並且從來不知道你可以這樣做(使用「參考「與值類型)!但是,這有其侷限性:不能將該「引用」存儲爲集合的一個元素。 – ToolmakerSteve 2017-02-03 16:58:16
我認爲唯一的辦法就是重新編寫和直通所有屬性,運算符和方法,就像這樣:
public class PointReference {
private Point point;
public int X { get { return point.X; } set { point.X = value; } }
}
(類名稱的改動意; CPoint
不是很表情)
這樣的事情?
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
是的,除了它爲每個操作符和轉換都做了這個工作非常煩人...... – baruch 2012-01-04 22:43:24
查看已添加的隱式轉換 – 2012-01-04 22:56:17
你爲什麼要/需要這樣一個包裝? – Xint0 2012-01-04 22:37:57
@ Xint0就像我說的,用它作爲參考類型。 – baruch 2012-01-04 22:42:18
@barunch:在這之前,請考慮**有一個原因**爲什麼這種簡單的類型被定義爲'structs'。其中之一是,'struct'分配速度非常快,在繪圖方法中使用'Point'結構,分配和釋放速度至關重要。 – Tigran 2012-01-04 22:54:58