C# 如何将 hack/fix 'this' 关键字放入结构中?
C# How to hack/fix 'this' keyword into a struct?
显然您不能在结构的方法中使用关键字 "this"。
请注意,在下面的示例中,我没有明确键入 "this",但当我引用属性 "X" 或 "Y".
时,它是隐含的
我的结构:
public struct Coord
{
public int X;
public int Y;
public Coord(int x, int y)
{
X = x;
Y = y;
}
// some other methods omitted
public List<int> GetPossibles()
{
return LaurenceAI.Values.Where(n => LaurenceAI.Possibilities[X, Y, n]).ToList();
}
}
用法示例:
foreach(int numeral in targetCoord.GetPossibles())
{
//do stuff
}
错误:
Error 1 Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. C:\Projects\Sodoku\SodokuSolver\Sodoku\LaurenceAI.cs 367 74 Sodoku
问题:
- 结构中的方法不能使用关键字的技术原因是什么"this"?
- 有没有一种优雅的方法来解决这个问题,这样我就不必在每次需要给定坐标的可能数字列表时都手写反射代码?
原因是结构是按值传递的,而不是按引用传递的。在这种情况下使用 this
通常不会产生您想要的结果 - 它会访问副本的 this
指针,而不是外部对象,并且当您进行任何分配时它会非常混乱' 显示在外部调用中。在这种特定情况下这很烦人,但总的来说它会阻止更多奇怪的错误。
错误消息实际上为您提供了一个相当合理的解决方案——先复制值。做类似的事情:
public List<int> GetPossibles()
{
var localX = X;
var localY = Y;
return LaurenceAI.Values.Where(n => LaurenceAI.Possibilities[localX, localY, n]).ToList();
}
显然您不能在结构的方法中使用关键字 "this"。 请注意,在下面的示例中,我没有明确键入 "this",但当我引用属性 "X" 或 "Y".
时,它是隐含的我的结构:
public struct Coord
{
public int X;
public int Y;
public Coord(int x, int y)
{
X = x;
Y = y;
}
// some other methods omitted
public List<int> GetPossibles()
{
return LaurenceAI.Values.Where(n => LaurenceAI.Possibilities[X, Y, n]).ToList();
}
}
用法示例:
foreach(int numeral in targetCoord.GetPossibles())
{
//do stuff
}
错误:
Error 1 Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. C:\Projects\Sodoku\SodokuSolver\Sodoku\LaurenceAI.cs 367 74 Sodoku
问题:
- 结构中的方法不能使用关键字的技术原因是什么"this"?
- 有没有一种优雅的方法来解决这个问题,这样我就不必在每次需要给定坐标的可能数字列表时都手写反射代码?
原因是结构是按值传递的,而不是按引用传递的。在这种情况下使用 this
通常不会产生您想要的结果 - 它会访问副本的 this
指针,而不是外部对象,并且当您进行任何分配时它会非常混乱' 显示在外部调用中。在这种特定情况下这很烦人,但总的来说它会阻止更多奇怪的错误。
错误消息实际上为您提供了一个相当合理的解决方案——先复制值。做类似的事情:
public List<int> GetPossibles()
{
var localX = X;
var localY = Y;
return LaurenceAI.Values.Where(n => LaurenceAI.Possibilities[localX, localY, n]).ToList();
}