如何使用Generic对象访问没有共同祖先的不同对象的属性?

时间:2015-05-13 12:43:55

标签: c# object generics

我有这段代码,基本上它在“X”HttpBinding中设置了相同的属性。

switch (serviceEndpoint.Binding.GetType().ToString())
{
case "System.ServiceModel.WSHttpBinding":
    WSHttpBinding _wsBinding = (WSHttpBinding)serviceEndpoint.Binding;
    _wsBinding.MaxBufferPoolSize = maxSize;
    _wsBinding.MaxReceivedMessageSize = maxSize;
    _wsBinding.OpenTimeout = timeOut;
    _wsBinding.ReaderQuotas.MaxStringContentLength = maxSize;
    break;

case "System.ServiceModel.WebHttpBinding":
    WebHttpBinding _webBinding = (WebHttpBinding)serviceEndpoint.Binding;
    _webBinding.MaxBufferPoolSize = maxSize;
    _webBinding.MaxBufferSize = maxSize;
    _webBinding.MaxReceivedMessageSize = maxSize;
    _webBinding.OpenTimeout = timeOut;
    break;

default:
case "System.ServiceModel.BasicHttpBinding":
    BasicHttpBinding _basicBinding = (BasicHttpBinding)serviceEndpoint.Binding;
    _basicBinding.MaxBufferPoolSize = maxSize;
    _basicBinding.MaxBufferSize = maxSize;
    _basicBinding.MaxReceivedMessageSize = maxSize;
    _basicBinding.OpenTimeout = timeOut;
    break;
}

对象serviceEndpoint.Binding每次都可能不同。

我想知道,如果我可以这样做:

object _Binding = serviceEndpoint.Binding;
_Binding.MaxBufferPoolSize = maxSize;
_Binding.MaxBufferSize = maxSize;
_Binding.MaxReceivedMessageSize = maxSize;
_Binding.OpenTimeout = timeOut;

但是,如果我把它,我有一个错误,因为我没有获得强制转换对象的属性。

1 个答案:

答案 0 :(得分:0)

不幸的是,这些属性并没有在共同的祖先上定义,所以剩下的唯一方法就是使用反射。 dynamic关键字是一个很好的捷径:

dynamic binding = serviceEndpoint.Binding;

binding.MaxBufferPoolSize = maxSize;
binding.MaxBufferSize = maxSize;
binding.MaxReceivedMessageSize = maxSize;
binding.OpenTimeout = timeOut;

但是通过这样做,您将失去在编译时检测强制转换错误的能力。由你来决定它是否值得。