使用指令预处理器处理多个目标框架

时间:2018-08-28 14:27:46

标签: c# visual-studio .net-core .net-standard

我创建了一个针对Net Standard 2.0Net Framework 4.6.2的Net Standard类库来处理这两个框架。在Net Framework中,我需要区分它是Web API项目还是Web Application项目。这就是我想要的。

using System;
using System.Linq;

#if (netcoreapp2.0 || netcoreapp2.1)
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
#endif

//net462 || net47 || net471 || net472
#if (NETFX)
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
#endif

namespace TestNetStandard
{
    //FOR NET MVC WEB
    public class ExceptionValidationAttribute : System.Web.Mvc.IExceptionFilter
    {
    }

    //FOR NET MVC API
    public class ExceptionValidationAttribute : System.Web.Http.Filters.ExceptionFilterAttribute
    {
    }

    //For NET CORE
    public class ExceptionValidationAttribute : Microsoft.AspNetCore.Mvc.Filters.ExceptionFilterAttribute
    {
    }
}

那么,ExceptionValidationAttribute类继承不同的类时,是否可以使用预处理指令创建单个类?是,如何实现?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情

#if ASPNETMVC
using ExceptionValidationAttributeParent = System.Web.Mvc.IExceptionFilter;
#elif ASPNETWEBAPI
using ExceptionValidationAttributeParent = System.Web.Http.Filters.ExceptionFilterAttribute;
#elif ASPNETCORE
using ExceptionValidationAttributeParent = Microsoft.AspNetCore.Mvc.Filters.ExceptionFilterAttribute;
#else
// default case but maybe redundant 
using ExceptionValidationAttributeParent = SomeFakeParentClass;
#endif



namespace TestNetStandard
{
    public class ExceptionValidationAttribute : ExceptionValidationAttributeParent
    {
        ...
    }
}