如何引用我的代码在其中执行的任务?
ISomeInterface impl = new SomeImplementation();
Task.Factory.StartNew(() => impl.MethodFromSomeInterface(), new MyState());
...
void MethodFromSomeInterface()
{
Task currentTask = Task.GetCurrentTask(); // No such method?
MyState state = (MyState) currentTask.AsyncState();
}
Run Code Online (Sandbox Code Playgroud)
因为我正在调用一些接口方法,所以我不能只将新创建的任务作为附加参数传递.
我想using纯粹用于范围管理.我可以省略对实现的底层对象的显式引用IDisposable吗?
例如,给出这个声明:
class ITransactionScope : IDisposable {}
class TransactionGuard : ITransactionScope {...}
class DbContext
{
public IDisposable ITransactionScope()
{
return new TransactionGuard();
}
}
Run Code Online (Sandbox Code Playgroud)
我可以做以下事情:
void main()
{
var dbContext = new DbContext();
using (dbContext.TransactionScope())
{
// the guard is not accessed here
}
}
Run Code Online (Sandbox Code Playgroud)
声明中的TransactionGuard实例是否存活using?
鉴于这些接口和实现
interface IService {}
class Service : IService {}
Run Code Online (Sandbox Code Playgroud)
用通用方法
void Register<I>(I service)
{
var type = typeof(I);
}
Run Code Online (Sandbox Code Playgroud)
如何使以下几行与泛型类型保持一致?
Register<IService>(new Service()) // type is 'IService'
Register(new Service()); // type is 'Service'
Run Code Online (Sandbox Code Playgroud)
有两种选择:
IServie类型编译的