[英]Is it possible to exclude auto-generated files when importing classes from one C# project to another?
將類從一個 C# 項目導入另一個項目時,是否可以排除自動生成的文件?
我有一個基於從 proto 文件生成的類實現 GRPC 服務的項目。
此外,我還有另一個項目,我在其中測試第一個項目的類,例如 GRPC 服務。 在第二個項目中,我實現了一個 GRPC 客戶端,以使用相同的 proto 文件副本來測試 GRPC 服務。
問題是我導入了第一個項目的所有類,遺憾的是其中一些類是使用相同的 proto 文件生成的,並且有很多關於類名沖突的警告。
有沒有辦法在同一解決方案的項目之間僅導入特定文件?
我使用項目文件中的下一個指令來生成類:
<ItemGroup>
<Protobuf Include="Protos\Proto.proto" GrpcServices="Server" />
</ItemGroup>
<ItemGroup>
<Protobuf Include="Protos\Proto.proto" GrpcServices="Client" />
</ItemGroup>
我將第一個項目的類導入到第二個項目中,如下所示:
<ItemGroup>
<ProjectReference Include="..\core\First.csproj" />
</ItemGroup>
警告是這樣的:
TestClient.cs(53,29): warning CS0436: The type 'Type1' in '/folder1/solution/test_project/obj/Debug/netcoreapp3.1/Class1.cs' conflicts with the imported type 'Type1' in 'Project1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in '/folder1/solutiion/test/obj/Debug/netcoreapp3.1/Class1.cs'. [/folder1/solution/test_project/Project2.csproj]
我通常在單個程序集中創建我的 proto 文件及其生成的代碼,然后從服務和客戶端程序集中引用該程序集。 這保留了一次生成的代碼,並消除了重復的代碼生成。
您不能有條件地導入類型,但可以在將第一個項目導入到第二個項目時為第一個項目中的類型添加extern 別名。
將以下代碼段添加到您的第二個 .csproj
<Target Name="ChangeAliasesOfStrongNameAssemblies" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'First'">
<Aliases>FirstExtern</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
您現在可以明確定義要使用的類型:將其添加到 .cs 代碼中的所有用途之上:
extern alias FirstExtern;
並通過指定定義的別名引用第一個項目中的類型:
FirstExtern::First.Type1 variable;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.