首页 > 解决方案 > 在外部项目中定义

问题描述

我有2个项目。嵌套项目有 2 个模型:Model1inModel1Out.

namespace Test.Nested
{
    public class Model1in
    {
#if NATIVE
        public static explicit operator Model1in(Model1Out model)
        {
            return model == null ? null : new Model1in();
        }
#endif
    }

    public class Model1Out
    {
#if NATIVE
        public static explicit operator Model1Out(Model1in model)
        {
            return model == null ? null : new Model1Out();
        }
#endif     
}

但在其他项目中,我想将对象 Model1in 转换为 Model1Out 并返回。

#define NATIVE

namespace Test.Native
{
     ....
     Model1Out model = (Model1Out)Model1in;
}

编译器生成错误并且无法识别模型转换块。要求实施。原来他只是没有看到块#define NATIVE。怎么了?我添加对项目的引用NestedNative使用他并在项目设置中定义常量。

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DefineConstants>DEBUG;NATIVE</DefineConstants>
</PropertyGroup>

如果我在项目中一直使用这个工具Nested- 没问题,但我有其他项目,这个块不能是我们,我想隐藏implicit|explicit建筑。

标签: c#.net-corepreprocessor-directiveexplicit

解决方案


I don't completely understand your question. Are these the steps you are following?

  1. Compile Test.Nested without NATIVE defined, creating Test.Nested.dll
  2. Now in Test.Native, add a reference to Test.Nested.dll
  3. Try to compile Test.Native with NATIVE defined to create Test.Native.dll
  4. Receive a compiler error that operator Model1Out() is undefined

If that is your problem, then here is what is happening.

The #if directive is used only when first compiling a project. If you compile Test.Nested.dll without NATIVE defined, then the code between #if NATIVE and #endif will not be included in Test.Nested.dll at all. It is as if you compiled this code:

namespace Test.Nested
{
    public class Model1in
    {
    }

    public class Model1Out
    {
    } // I added a missing end brace here
}

Your classes are empty, and Test.Nested.dll has no conversions defined.

If Test.Nested is empty because it wasn't compiled with NATIVE defined, then when you compile Test.Native, you will get an error regardless of whether NATIVE is defined because the conversion block was never included in Test.Nested.dll.

In order to use the conversion blocks, you must define NATIVE when you compile Test.Nested.


推荐阅读