首页 > 解决方案 > 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> 呢?...

谢谢你。

标签: c#generics

解决方案


您需要将您的类定义如下 public static void NewBinding(string pCfgName, string pAddr, out T result) where T : System.ServiceModel.Channels.Binding, new()


推荐阅读