我有一个多边形类,它存储一个Microsoft.Xna.Framework.Vector2列表作为多边形的顶点.创建多边形后,我希望其他类能够读取顶点的位置,但不能更改它们.
我目前通过这个字段公开顶点:
/// <summary>
/// Gets the vertices stored for this polygon.
/// </summary>
public List<Vector2> Vertices
{
get { return _vertices; }
}
List<Vector2> _vertices;
Run Code Online (Sandbox Code Playgroud)
但是,您可以使用以下代码更改任何顶点:
Polygon1.Vertices[0] = new Vector2(0, 0);
Run Code Online (Sandbox Code Playgroud)
要么
Polygon1.Vertices[0].X = 0;
Run Code Online (Sandbox Code Playgroud)
如何限制其他类只能读取这些顶点的属性,而不能将新的顶点设置为我的列表?我唯一能想到的是将副本传递给请求它的类.
请注意,Vector2是一个结构,它是XNA框架的一部分,我无法更改它.
谢谢.
在你的类型上有一个只读接口(但是因为它是内置的类型),并且在ReadOnlyCollection中传递出一个版本 .
public ReadOnlyCollection<IReadOnlyVector2> Vertices
{
get { return (from v in _vertices
select new DerivedVector2 { WrappedVector2 = v })
.Cast<IReadOnlyVector2>().ToList().AsReadOnly();
}
}
List<Vector2> _vertices;
interface IReadOnlyVector2 {
.. only RO getters and no setters
}
class DerivedVector2 : IReadOnlyVector2{
public Vector2 WrappedVector2 { get; internal set;}
.
.
.
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
376 次 |
| 最近记录: |