传入委托作为参数时返回泛型类型的方法
我正在尝试“通用”我们散布在系统中的一些代码。
我想:
- 返回一个泛型类型,
- 传入某种包含要调用的方法的委托。
我对泛型还很陌生,所以非常感谢任何帮助。
下面是我的手指在空中的位置(!)
public static T ReturnSingleObject<T>(Func<string, int, T> dynamicSignature)
{
T returnValue;
ServiceReference wCFService;
try
{
wCFService = new BusinessServiceClient();
returnValue = dynamicSignature();
//returnValue = wCFService.AMETHOD(PARAM1, PARAM2);
return returnValue;
}
catch (Exception)
{
if (wCFService != null) wCFService.Abort();
throw;
}
finally
{
if (wCFService != null) wCFService.Close();
}
}
I'm trying to 'genericize' some code we have spattered around our system.
I want to:
- return a generic type,
- pass in some kind of delegate containing the method to be called.
I'm pretty new to generics so any help appreciated.
Below is where my finger in the air is(!)
public static T ReturnSingleObject<T>(Func<string, int, T> dynamicSignature)
{
T returnValue;
ServiceReference wCFService;
try
{
wCFService = new BusinessServiceClient();
returnValue = dynamicSignature();
//returnValue = wCFService.AMETHOD(PARAM1, PARAM2);
return returnValue;
}
catch (Exception)
{
if (wCFService != null) wCFService.Abort();
throw;
}
finally
{
if (wCFService != null) wCFService.Close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的dynamicSignature函数似乎缺少几个参数,因此您需要添加这些参数。另外,您可以将 return 语句移至 try 块之外的底部,并将返回值初始化为默认值:
It looks like you're missing a couple parameters for your dynamicSignature function, so you'll need to add those. Also, you might move your return statement to the bottom, out of the try block, and initialize your return value to the default value: