[英]Why does New Task<object>( (Func<Task<object>>)( async ( ) => { } ) work when new Task<Foo>( … ) does not?
Why does new Task<object>( (Func<Task<object>>)( async ( ) => { } )
work when new Task<Foo>( ... )
does not? 为什么当new Task<Foo>( ... )
不起作用时, new Task<object>( (Func<Task<object>>)( async ( ) => { } )
起作用?
This works: 这有效:
private static Task<object> Works( ) {
return new Task<object>( ( Func<Task<object>> )( async ( ) => {
return new object( );
} ), new CancellationTokenSource( ).Token );
}
But this doesn't: 但这不是:
private static Task<Foo> Doesnt( ) {
return new Task<Foo>( (Func<Task<Foo>>)(async ( ) =>{
return new Foo( );
} ), new CancellationTokenSource( ).Token );
}
Replace Foo with anything that is not an object (or any other primitive I'm guessing) and you will see that you get the same error message over the red squigglies : The best overloaded method match for 'System.Threading.Task.Task<Foo>.Task(object, System.Threading.Tasks.TaskCreationOptions)' has some invalid arguments
将Foo替换为不是对象的任何东西(或我猜到的任何其他原语),您将看到在红色的花键上得到相同的错误消息: The best overloaded method match for 'System.Threading.Task.Task<Foo>.Task(object, System.Threading.Tasks.TaskCreationOptions)' has some invalid arguments
I even see the overloaded method to which it is referring... and yet why does it think that I am trying to call THAT method when I use Func<Task<Foo>>
but NOT when I use Func<Task<object>>
????? 我甚至看到了重载方法,它是指......,但为什么它认为我试图调用该方法,当我使用Func<Task<Foo>>
而不是当我用Func<Task<object>>
?????
This works with object (or Object) but FAILS with my class. 这适用于对象(或对象),但对于我的类却失败。 I even tried it with another class object (Window) and THAT failed. 我什至尝试了另一个类对象(Window),但失败了。
In response to claims that the first bit does not compile I have been able to compile the following : 为了回应有关第一位不编译的说法,我已经能够编译以下内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncFlubbery {
class Program {
private static Task<object> Works( ) {
return new Task<object>( ( Func<Task<object>> )( async ( ) => {
return new object( );
} ), new CancellationTokenSource( ).Token );
}
static void Main( string[ ] args ) {
Works( ).Start( );
Console.WriteLine( "Press Enter To Begin..." );
Console.ReadLine( );
}
}
}
This is a simple case of type casting. 这是类型转换的简单情况。
It boils down to this code: 归结为以下代码:
Func<Task<object>> fto = null;
Func<object> fo = fto; //this is a fine cast
Func<Task<Foo>> ftf = null;
Func<Foo> ff = ftf; //this is **NOT** a fine cast
Since Task<object>
derives from object
the first cast is OK. 由于Task<object>
从object
派生的,因此第一个转换是正确的。
But Task<Foo>
does not derive from Foo
so the cast is invalid. 但是Task<Foo>
不是从Foo
派生的,因此强制类型转换无效。
So, even though the first code compiles it won't work as expected at run-time. 因此,即使第一个代码编译了,它也不会在运行时按预期运行。 Both bits of code are ultimately faulty. 代码的两个位最终都是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.