Can I make a preprocessor directive dependent on the .NET framework version?

北慕城南 提交于 2019-12-04 01:10:09
Joshua Rodgers

You can take a look at another question on Stack Overflow that illustrates how to set conditional constants through the project file's XML: Detect target framework version at compile time

Then using that you can determine if you should use the .NET 4 overloads or your own library.

Yes, I think it makes sense (for your particular case, since the change is relatively minor), though obviously that sort of thing could scale out of control fairly quickly.

IMHO, the most logical way to go about it would be to create different solution/project configurations for each version, then define a custom symbol (say, NET40) in your 4.0 configurations, then use that with an #if. I'm not certain if configurations will allow you to change the runtime version (that would obviously be the perfect solution), but your worst-case is having to change the version manually.

EDIT: I just saw the answer linked to in Joshua's answer, and that seems like a more streamlined solution, but I'll leave this here anyway, since it does, strictly speaking, answer the question.

Tomas Kubes

You can prepare your code for .NET 4.0 and write the similar code for the .NET 3.5 base on framework detection.

#if NOT_RUNNING_ON_4
public static class GuidExtensions
{
   public static bool TryParse(this string s, out Guid result)
   {
       if (s.IsNullOrEmpty())
           return null;
       try
       {
          return new Guid(s);
       }
       catch (FormatException)
       {
          return null;
      }
   }
}
#else
    #error switch parsing to .NET 4.0
#endif

And put his line to your *.csproj

<DefineConstants Condition=" '$(TargetFrameworkVersion)' != 'v4.0' ">NOT_RUNNING_ON_4</DefineConstants>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!