C# Macro definitions in Preprocessor

前端 未结 10 1730
走了就别回头了
走了就别回头了 2020-11-29 04:16

Is C# able to define macros as is done in the C programming language with pre-processor statements? I would like to simplify regular typing of certain repeating statements

10条回答
  •  天涯浪人
    2020-11-29 04:50

    There is no direct equivalent to C-style macros in C#, but inlined static methods - with or without #if/#elseif/#else pragmas - is the closest you can get:

            /// 
            /// Prints a message when in debug mode
            /// 
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public static unsafe void Log(object message) {
    #if DEBUG
                Console.WriteLine(message);
    #endif
            }
    
            /// 
            /// Prints a formatted message when in debug mode
            /// 
            /// A composite format string
            /// An array of objects to write using format
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public static unsafe void Log(string format, params object[] args) {
    #if DEBUG
                Console.WriteLine(format, args);
    #endif
            }
    
            /// 
            /// Computes the square of a number
            /// 
            /// The value
            /// x * x
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public static double Square(double x) {
                return x * x;
            }
    
            /// 
            /// Wipes a region of memory
            /// 
            /// The buffer
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public static unsafe void ClearBuffer(ref byte[] buffer) {
                ClearBuffer(ref buffer, 0, buffer.Length);
            }
    
            /// 
            /// Wipes a region of memory
            /// 
            /// The buffer
            /// Start index
            /// Number of bytes to clear
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public static unsafe void ClearBuffer(ref byte[] buffer, int offset, int length) {
                fixed(byte* ptrBuffer = &buffer[offset]) {
                    for(int i = 0; i < length; ++i) {
                        *(ptrBuffer + i) = 0;
                    }
                }
            }
    

    This works perfectly as a macro, but comes with a little drawback: Methods marked as inlined will be copied to the reflection part of your assembly like any other "normal" method.

提交回复
热议问题