我有一个C#项目,它被用作Visual Studio扩展的一部分。
要支持早期版本的VS,项目设置为Target framework
.NET Framework 3.5。
该项目引用System.ServiceModel
。
根据运行的Visual Studio版本,将使用不同版本的System.ServiceModel
。 VS2008将使用.NET 3.5版本的DLL,而VS2012将在运行时使用.NET 4.5版本,无论项目目标框架如何。
我的问题是在.NET 4中HttpTransportBindingElement添加了一个名为DecompressionEnabled的属性。因为我的目标是.NET 3.5,所以无法通过更改此属性进行编译;但是,我确实需要改变它的价值。
我用来在运行时更改属性的工作是使用反射:
public static void DisableDecompression(this HttpTransportBindingElement bindingElement)
{
var prop = bindingElement.GetType()
.GetProperty("DecompressionEnabled",
BindingFlags.Public | BindingFlags.Instance);
if (null != prop && prop.CanWrite)
{
prop.SetValue(bindingElement, false, null);
}
}
解决方案有效,但我想知道是否有更好的设计模式来处理它,而不需要反射。
答案 0 :(得分:1)
请参阅:Detect target framework version at compile time
public static void DisableDecompression(this HttpTransportBindingElement bindingElement)
{
#if RUNNING_ON_4
bindingElement.DecompressionEnabled = false;
#endif
}
将.NET版本的版本设置为发布后,将优化对DisableDecompression
的所有引用。