Task: reuse C# code in different projects but without project referencing (don’t want extra dll/references just because of a small utility class). There’re 4 projects, one of them contains utility class which is currently source-code-linked by other 3 projects. Problem: once one of the projects starts referencing one of others (for some other needs), the compiler starts complaining (obviously) that there’s the same class (with the same namespace) in these projects.

Are there any solutions other than to move the class to separate project or to make 4 copies of the class for each project and maintain them separately?

I wonder is there a way to source link files so that the class inside a file gets project-specific unique namespace…

有帮助吗?

解决方案

I wonder is there a way to source link files so that the class inside a file gets project-specific unique namespace…

Well you could use preprocessor directives:

#if PROJECT_FOO
namespace Foo
#elif PROJECT_BAR
namespace Bar
#elif PROJECT_BAZ
namespace Baz
#endif

... and then link the file into each project, defining appropriate symbols in the project properties.

But I would thoroughly recommend against it. It's horrible, and it's certainly not how C# was designed to be written.

Just break it out into a separate project - you're bound to find you want more and more code like this anyway.

其他提示

To the question:

"Are there any solutions other than to move the class to separate project or to make 4 copies of the class for each project and maintain them separately?"

The short answer is: no, there isn't. Or at least, there is no elegant way of doing that.

The right way is indeed to make it part of a referenced project. But you don't have to make a project that will contain JUST that utility class! Instead, make it a project holding multiple simple utilities with as little dependencies as possible and share it across your solutions. Much easier and cleaner this way.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top