我想减少一些额外的电话,并将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/

10-10 11:07