我有這個代碼,基本上它在「X」HttpBinding中設置了相同的屬性。如何使用Generic對象訪問不具有共同祖先的不同對象的屬性?
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;
但如果我把這個,我有一個錯誤,因爲我沒有得到投對象的屬性。
在類型的*名稱*上做一個switch-case是* reeallly *糟糕。考慮使用'is'運算符代替:'if(serviceEndpoint.Binding是WebHttpBinding)'。或安全轉換 - 'var webBinding = serviceEndpoint.Binding as WebHttpBinding;如果(webBinding!= null)...' – dcastro