c# - C# 泛型方法:有什么问题,如果可能的话?
问题描述
我正在尝试做这样的事情:
public static T NewBinding2<T>(string pCfgName, string pCfgSuffix, string pAddr) where T : System.ServiceModel.Channels.Binding, new()
{
T result = null;
// when pCfgSuffix is not emptry - try custom binding name...
string cfgId = (!string.IsNullOrEmpty(pCfgSuffix) ? StrUtils.IncludeTrailing(pCfgName, ".") + pCfgSuffix : pCfgName);
// try create binding according to config...
try { result = new T(cfgId); }
catch (Exception ex1)
{
Trace.WriteLine(TrcLvl.TraceError, TrcLvl.TraceError ? string.Format("NewBinding<{0}>.1[{1}]({2}).ERR:{3}\nat {4}",
typeof(T), cfgId, pAddr, ErrorUtils.FormatErrorMsg(ex1), ErrorUtils.FormatStackTrace(ex1)) : "");
// if there was unsuccefull attempt with name suffix - then we need to try also without suffux...
if (!string.IsNullOrEmpty(pCfgSuffix))
{
cfgId = pCfgName;
try { result = result = new T(cfgId); }
catch (Exception ex2)
{
Trace.WriteLine(TrcLvl.TraceError, TrcLvl.TraceError ? string.Format("NewBinding<{0}>.2[{1}]({2}).ERR:{3}\nat {4}",
typeof(T), cfgId, pAddr, ErrorUtils.FormatErrorMsg(ex1), ErrorUtils.FormatStackTrace(ex1)) : "");
}
}
if (result == null)
{
// in case of failure - create with default settings
result = new T();
result.Name = cfgId;
}
}
return result;
}
BasicHttpBinding bnd = NewBinding<BasicHttpBinding>("bndBasicHttp", "ScreensApi", "http://....");
但是 C# 编译器向我报告了很多错误(VS 2012,.NET 4.5):
1>WcfUtils.cs(94,28,94,40): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
1>WcfUtils.cs(104,45,104,57): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
但为什么?!System.ServiceModel.Channels.Binding 具有默认构造函数,并且在哪里为泛型指定...
有可能做这样的事情吗?
我只是想优化我的代码,让它更短。
更新:
我尝试将 Func<string, T> 用于参数化构造函数,但这似乎没有意义 - 在我的情况下,我看不到如何使用它,因为 cfgId 是在方法中准备的变量,所以我应该指定什么作为参数那么 Func<string, T> 呢?...
谢谢你。
解决方案
您需要将您的类定义如下 public static void NewBinding(string pCfgName, string pAddr, out T result) where T : System.ServiceModel.Channels.Binding, new()
推荐阅读
- javascript - 使用 jquery 单击多个 div 时添加和删除类
- javascript - 如何在 Mongoose/MongoDB 中将按最多匹配数排序的结果返回到最少?
- lua - 在 lua 中访问数组元素效果不佳
- sql - 仅使用另一个表的 rowid 创建虚拟表
- php - 自定义页面模板无法识别定义在
- python - 打印正在以相反的字母顺序打印所有字母而不是单词
- sql - Varchar 到日期转换
- oracle - 嵌套在循环中的案例,PLS-00103:遇到符号“;” 预期以下情况之一时:案例
- swift - 如何模糊父视图,同时保持子视图不模糊
- python - 如何检查数组A中的元素是否存在于数组B中并返回B的索引