我写了下面这个方法:
async Task<T> Load<T>(Func<T> function)
{
T result = await Task.Factory.StartNew(() =>
{
IsLoading = true;
T functionResult = function.Invoke();
IsLoading = false;
return functionResult;
});
return result;
}
我有两个问题:
Can I simplify the code?
I can pass any parameterless method/function to this method to get a return type of any type. E.g.:
string GetString()
By saying:
string someString = await Load(GetString);
Is there a way I could make this method more generic so that I could pass methods with parameters as well? E.g. One single method that would also accept:
string GetString(string someString) string GetString(string someString, int someInt)
This might look like:
string someString = await Load(GetString("string")); string someString = await Load(GetString("string", 1));
This obviously doesn't work, but as the
Load<T>
method doesn't reference the parameters, I feel this should be possible somehow.
IsLoading
的目的是什么? - Robert Harvey.Invoke()
来调用委托。您可以简单地使用T functionResult = function()
。生成的代码没有区别,但我倾向于将.Invoke()
与基于反射的动态调用相关联。 - xanatosawait Load(() => GetString("string"))
应该可以正常工作。 - HeinziIsLoading
是我在 WPF 数据绑定中使用的一个属性 - 这个方法是LoadingViewModel
基类的一部分。 - Chris Mack