2016-04-22 436 views
0

我试图将一个字符串传入一个方法,并基于传入的字符串,实例化BasicHttpBinding或WSHttpBinding。以下if语句在我的代码中。C#在if语句中声明变量,通用基类

if(bindingObject == "basic") 
{System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();} 
else 
{System.ServiceModel.WSHttpBinding binding = new System.ServiceModel.WSHttpBinding(); 

此代码给我的错误

“结合”的名字没有出现在目前情况下

从我的研究好像我一定要使用公共基类存在在两个服务模型之间,如果我想使用名为绑定的变量,无论我需要使用哪个ServiceModel。

我的问题是,什么是常见的基类将工作?还是有办法做到这一点。我发现的最接近的是System.ServiceModel.Channels.Binding但后来我得到如

不包含“MaxBufferPoolSize”,没有扩展方法定义的错误“MaxBufferPoolSize”接受tyep的第一个参数“ System.ServiceModel.Channels.Binding”可以发现

+0

你不能像这样声明一个不同类型的变量。 –

+0

你可以重构if - 然后阻塞到一个泛型方法,然后返回适当的绑定。即公共T GetBinding ();' – Tim

回答

0

问题是因为局部变量的作用域。据C#规格从MSDN确定范围,

作用域可以嵌套,并且内部范围可以从重新声明外部范围的名称的含义(在此不,但是,除去由§1所施加的限制。20在嵌套块中,不可能在封闭块中声明一个与本地变量具有相同名称的局部变量)。

另一个从规范标识符作用域,

对于给定的标识符如在表达式或声明简单名称的每次出现,局部变量声明空间内,立即封闭块,或开关在这种情况下,在紧邻封闭块或开关块内的表达式或声明器中,与其简单名称相同标识符的其他每次出现必须引用同一个实体。该规则确保名称的含义在给定块,开关块,for-,foreach或using语句或匿名函数中始终保持相同。

现在移动到您所遇到的错误: BasicHttpBinding从HttpBindingBase从Binding衍生和实施IBindingRuntimePreferences的。 WSHttpBinding是从WSHttpBindingBase中派生而来的,派生自Binding并执行IBindingRuntimePreferences

但属性MaxBufferPoolSize驻留在HttpBindingBase和WsHttpBindingBase中,而不在其共同的父项BindingIBindingRuntimePreferences中。这意味着你不能使用普通的类来表示这些绑定。而应该使用dynamic作为在运行时绑定类型而不是编译时的类型。

Public dynamic GetBinding(string bindingObject) 
{ 
    if (bindingObject == "basic") 
    { 
     binding = new System.ServiceModel.BasicHttpBinding(); 
    } 
    else 
    { 
     binding = new System.ServiceModel.WSHttpBinding(); 
    } 

    return binding; 
    } 
+0

This与几个警告一起工作。首先,我必须声明一个动态绑定的变量;在GetBinding方法中。然后,我意识到这是.net 3.5代码,必须将该项目转换为4.0 – Bryan

1

第一:既BasicHttpBindingBasicHttpBinding需要无论是从同一个基类派生或实现相同interface

如果你正在使用Visual Studio,你可以将光标放在类型上请按f12查看它们来自哪些类型以及它们实现的接口。适合使用的类型取决于您想要对它们执行的操作。

根据对BasicHttpBindingWSHttpBinding,将公共基类似乎System.ServiceModel.Channels.Binding文档,

您应该使用f12反正检查,因为可能有在那里的接口定义,你需要使用会员。

其次,你必须声明一下你的if语句

System.ServiceModel.Channels.Binding binding; 
if(bindingObject == "basic") 
{ 
    binding = ... 
} 
else 
{ 
    binding = ... 
} 
+0

两个类最好的共同基础是'System.ServiceModel.Channels.Binding' –

+0

@ScottChamberlain我只是看着 –

+0

我认为OP将不得不投入到派生类访问属性虽然,如果他们试图设置的东西,一个绑定已经和另一个不。 – Tim

0

你可以使用枯萎绑定基类或接口IBindingRuntimePreferences范围之外,如果可以访问你需要的功能。

//System.ServiceModel.Channels.Binding binding; 
    System.ServiceModel.Channels.IBindingRuntimePreferences binding; 
    if(bindingObject == "basic") 
     binding = new System.ServiceModel.BasicHttpBinding();} 
    else 
     binding = new System.ServiceModel.WSHttpBinding(); 
0

这是完美的使用情况进行动态关键字

 dynamic binding; 
     if (bindingObject == "basic") 
     { 
      binding = new System.ServiceModel.BasicHttpBinding(); 
     } 
     else 
     { 
      binding = new System.ServiceModel.WSHttpBinding(); 
     } 

然后你就可以访问你面对以下

 binding.MaxBufferPoolSize = 10; 
+0

似乎很松散.... –