开发者

How to know if a type has been already declared in another source file in C#?

开发者 https://www.devze.com 2023-03-16 16:57 出处:网络
I have a source file in C# that holds all misc types for a project inside their own namespace. Example:

I have a source file in C# that holds all misc types for a project inside their own namespace. Example:

#define HELPER_FILE

using System;

namespace Helper
{
    public struct NormalBalance : INormalType
    {
        public int Position { get; set; }
        public float Normal { get; set; }
    }

    ...

}

Then, other files use these types. I want to distribute some of these to others in my team, but they don't need all of the files, or types, but some data structures are shared.

For example:

using System;

namespace DataPump
{
    public class Pumper
    {
        private Helper.NormalBalance[] norm;

        ...
    }

    ...

}

But this code depends on the previous file containing the Helper.NormalBalance type. I want a method to sync the files so that one knows of the existence of the other like in C++ where we could use a #define directive in the file that declares the type, and if the client file didn't see token defined, it will conditionally compile the type as follows:

(C++ code follows)

    class Pumper
    {

    private:

#ifndef HELPER_FI开发者_Go百科LE
        struct NormalBalance
        {
            int Position;
            float Normal;
        }

        NormalBalance[] norm;

#else

        Helper.NormalBalance[] norm;

#endif

        ...
    }

    ...

}

Unfortunately, the #define directive's scope in C# is only the file where it was declared. Is there any way to do this in C#? I need to know if the file is included in the project, or if, at least, a type has been previously defined and if not, define it again.


On the .NET Framework, if you wish to share a library of types, I would recommend packaging them into a single project. When built, it becomes an assembly that can be referenced like any other assembly. Define directives are used for different purposes and rarely so. They are less prevalent than in C++ development.


You can define "conditional compilation symbols" at project level.

But don't do that. It is much easier and more convinient to build source into an assembly and share all types. Trying to ifdef portions out will cause a lot of trouble for you and integrating 2 assemblies that use portions of your code inline will be nightmare as soon as portions will intersect. You just don't want such headache for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号