我正在尝试编写一个补间类,为此我有一个静态 Tweener.TweenTo
方法。在其中,我们启动一个线程以避免阻碍外部操作。该方法如下所示:
public static void TweenTo<T>(ref ITweenable<T> obj, T target, double ms)
{
new System.Threading.Thread(() => {
System.Threading.Thread.Sleep(5000)
obj.DoStuff(5,5) //throws exception because obj is a ref parameter
}).Start()
}
我知道在 lambda 中使用 ref 参数意味着它可能是悬空引用,但我需要能够使用它,以防用户尝试将值类型或结构传递给方法。我尝试过使用参数化线程启动,但这将事物强制为对象,而我无法使用该对象(拆箱等)。我还尝试过使用一个包含指向它的指针的包装类,但这会导致稍后的复杂化。
我想要一种在线程中使用此 ref 参数的方法,并且最好在其中保留其生命周期。
感谢任何帮助:D
编辑:奥利维尔的答案接近我需要的,但在某些情况下 MyClass 将是一个结构,并且只要有可能它就会重复。这意味着它将丢失引用并从错误的实例中给出值。
编辑 2:示例结构
public struct MyStruct : ITweenable<T> {
int x;
int y;
public MyStruct(int X) {
this.x=X;
}
public void DoStuff(int newX, int newY) {
this.x=newX;
this.y=newY;
}
}
public interface ITweenable<T> {
void DoStuff(int newX, int newY);
}
编辑3:我还没有测试过这个,所以当我测试过时,我会把它作为答案 - 现在已经测试过,不起作用:
public static void TweenTo<T>(ITweenable<T> obj, T target, double ms)
{
Func<ITweenable<T>> getTween = ()=>{return obj;}
new System.Threading.Thread(() => {
System.Threading.Thread.Sleep(5000)
getTween().DoStuff(5,5);
}).Start()
}
最佳答案
我建议传递 Action<ITweenable<T>>
启用分配。像这样:
public static void TweenTo<T>(ITweenable<T> obj, Action<ITweenable<T>> update, T target, double ms)
{
new System.Threading.Thread(() =>
{
obj.DoStuff();
update(new Tweenable<T>());
}).Start()
}
关于c# - 如果 "Error CS1628: Cannot use in ref or out parameter inside an anonymous method, lambda or query expression"如何在线程中使用 ref 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68971071/