我目前正在研究一种在C#中实现侵入式树结构的简单方法.因为我主要是C++程序员,所以我立即想要使用CRTP.这是我的代码:
public class TreeNode<T> where T : TreeNode<T>
{
public void AddChild(T a_node)
{
a_node.SetParent((T)this); // This is the part I hate
}
void SetParent(T a_parent)
{
m_parent = a_parent;
}
T m_parent;
}
Run Code Online (Sandbox Code Playgroud)
这工作但是...我无法理解为什么我必须在调用a_node.SetParent((T)this时)进行转换,因为我使用泛型类型限制... C#cast有成本,我想要不要在每个侵入式集合实现中传播这个演员......
我想根据给定的集合类型(使用反射)进行一些操作,而不管泛型类型.
这是我的代码:
void MyFct(Type a_type)
{
// Check if it's type of List<>
if (a_type.Name == "List`1")
{
// Do stuff
}
// Check if it's type of Dictionary<,>
else if (a_type.Name == "Dictionary`2")
{
// Do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
它现在有效,但对我来说很明显,它不是最安全的解决方案.
void MyFct(Type a_type)
{
// Check if it's type of List<>
if (a_type == typeof(List<>))
{
// Do stuff
}
// Check if it's type of Dictionary<,>
else if (a_type == typeof(Dictionary<,>))
{
// Do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
我也试过,它实际编译但不起作用...我也尝试测试给定集合类型的所有接口,但它暗示了集合中接口的排他性...... …
这是出于好奇我想问这个问题...
这是我的代码:
for (int i = 0; i < myList.Count - 1; ++i)
{
for (int j = i+1; j < myList.Count; ++j)
{
DoMyStuff(myList[i], myList[j]);
}
}
Run Code Online (Sandbox Code Playgroud)
非常简单的循环,但显然它只适用于 List ......但我想知道......我如何编写这个循环以使其独立于集合的类型(源自 IEnumerable ......)我的第一个想法:
IEnumerator it1 = myList.GetEnumerator();
while (it1.MoveNext())
{
IEnumerator it2 = it1; // this part is obviously wrong
while (it2.MoveNext())
{
DoMyStuff(it1.Current, it2.Current);
}
}
Run Code Online (Sandbox Code Playgroud) 首先,我正在使用XNA框架开发2D策略游戏.
我正在为我的游戏实施2D战争迷雾.图形部分已经完成并且工作得非常好,但我现在正试图实现这场战争迷雾的"逻辑"部分.
我创建了一个代表我的关卡的2D网格.每个框架,每个单元使用Bresenham的算法(它似乎是确定给定圆中哪些单元格的最佳方法)更新围绕它的圆圈.这实际上是有效的......当我想知道某个位置是否可见时,我只需要获得该单元的状态......
问题是,当我有大量的衍生单位时,我的游戏运行得如此缓慢......这个性能问题的第一个原因是,由于每个单元更新它周围的单元格,许多单元格会多次更新...但我看不出任何解决方案......
所以...也许我错了以这种方式实现它,或者我可能错过了一个明显的优化,但我有点卡住......
这是代码:
class LevelGridCell
{
public void SetVisible(float a_time)
{
if (m_visibleTime < a_time)
m_visibleTime = a_time;
}
public bool IsVisible(float a_time)
{
return (m_visibleTime != 0f && m_visibleTime >= a_time);
}
float m_visibleTime = 0;
}
class LevelGrid
{
public LevelGridCell GetAt(int a_x, int a_y)
{
return m_grid[a_x + a_y * m_width];
}
public void SetVisible(float a_time, int a_x, int a_y, float a_radius)
{
GetAt(a_x, a_y).SetVisible(a_time);
int intRadius = (int)(a_radius / m_cellSize);
int x = …
Run Code Online (Sandbox Code Playgroud)