gpt4 book ai didi

c# - 转换到泛型时忽略 T

转载 作者:太空宇宙 更新时间:2023-11-03 19:02:19 24 4
gpt4 key购买 nike

我正试图减少一些额外的调用,并将 5 分钟的问题变成 30 分钟的问题。有没有办法在不知道泛型类型的情况下转换对象?在下面的代码中,我想制作 Complete<T, T2>简单 Complete<T2> .

public void Complete<T, T2>(object sender, RunWorkerCompletedEventArgs args) 
where T2 : new()
{
ServiceContainer<T, T2> callback = (ServiceContainer<T, T2>)args.Result;
StateManager.BackgroundWorker result = (StateManager.BackgroundWorker)sender;
callback.func(result.state, callback.response);
}

所以我希望它看起来像这样:

public void Complete<T2>(object sender, RunWorkerCompletedEventArgs args) 
where T2 : new()
{
ServiceContainer<object, T2> callback = (ServiceContainer<object, T2>)args.Result;
StateManager.BackgroundWorker result = (StateManager.BackgroundWorker)sender;
callback.func(result.state, callback.response);
}

最佳答案

您可以像这样使用动态语言运行时:

public void Complete<T2>(object sender, RunWorkerCompletedEventArgs args) 
where T2 : new()
{
dynamic callback = args.Result;
dynamic result = sender;
callback.func(result.state, callback.response);
}

如果您不在方法中使用 T2(就像在您的示例中那样),您可以将其删除并使您的方法成为非通用方法。

关于c# - 转换到泛型时忽略 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34009382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com