在编译时检测c#版本

Kev*_*onn 10 c# preprocessor-directive

我有一个旧的c#代码行,看起来基本上是这样的:

foo.set_Parent(parent);
Run Code Online (Sandbox Code Playgroud)

它已经编好了多年.现在在VS2015中我收到错误:

CS0571'Foo.Parent.set':无法显式调用运算符或访问器

所以我可以改写这行:

foo.Parent=parent;
Run Code Online (Sandbox Code Playgroud)

这在VS2015中构建得很好,但是在VS2013中它给出了错误:

语言不支持'Foo.Parent'; 尝试直接调用访问器方法'Foo.get_Parent()'或Foo.set_Parent(Foo)'

因此,简单的解决方法是简单地根据正在运行的编译器版本来定义这两行.但是,如何检测正在执行的编译器版本?

而且,对于记录,不,我不能只是要求团队中的每个人同时升级到VS2015.

附加信息 - 对于每个闻到老鼠的人来说,我会继续拖出丑陋的真相,尽管我认为它不会改变任何东西.Foo类是来自一个古老的Borland集合体,它在Delphi中都是绑定的(是的,我们正在迁移,但还没有迁移).因此,编译为VS2013的实际代码如下所示:

using Borland.Vcl;
using RepGen;
using SnapReportsForm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace MigrantCOM {
   [ComVisible(true)]
   [Guid("48245BA3-736B-4F98-BDC5-AD86F77E39F4")]
   [ProgId("MigrantCOM.Exports")]
   [ClassInterface(ClassInterfaceType.AutoDual)]
          public class MigrantCLRExports {   // : MarshalByRefObject 
      public string Test(string s) { return s+s; }
   }

   [ComVisible(true)]
   [Guid("1154D364-B588-4C31-88B9-141072303117")]
   [ProgId("MigrantCOM.SnapRepCOM")]
   [ClassInterface(ClassInterfaceType.AutoDual)]
   public class SnapRepCOM {
      TRepGen repGen;
      TStringList snapRefs=new TStringList();
      TForm parent=new TForm(null);
      TMemo designerMemo;
      List<TReference> references=new List<TReference>();
      TRunAsSnapContext runAsSnapContext=new TRunAsSnapContext();

      public SnapRepCOM() {
         designerMemo=new TMemo(parent); designerMemo.set_Parent(parent);
         ...
      }
Run Code Online (Sandbox Code Playgroud)

因此,实例化的类是Borland.Vcl.TMemo,它是旧Delphi程序集的一部分.

ken*_*n2k 1

我将其作为答案,链接图像比在评论中更适合。

因此,如果您想使用 VS 2015,但仍然使用多年来运行的 C# 语言的相同版本,您可以将您的项目配置为针对特定版本:

在此输入图像描述

这会添加<LangVersion>5</LangVersion>到 csproj.