How to declare a method in C ++ / CLI that will be considered as an extension method in C #?

I am writing a .NET assembly in C ++ / CLI that will be used in our C # application. I would like the application to treat some of the C ++ methods as extension methods. Is there any attribute that I can apply to the declaration to indicate that the method should be considered as an extension method from C #?

+3
source share
3 answers

Make this a static method in a non-nested, nonequivalent static class, with the attribute Extensionapplied to the class and method.

, ++/CLI... . , # , , . , , .

+5

, ++/CLI:

using namespace System;

namespace CPPLib 
{
    [System::Runtime::CompilerServices::Extension]
    public ref class StringExtensions abstract sealed
    {
    public: 
        [System::Runtime::CompilerServices::Extension]
        static bool MyIsNullOrEmpty(String^ s)
        {
            return String::IsNullOrEmpty(s);
        }
    };
}

, #:

using CPPLib;

namespace CShartClient
{
    class Program
    {
        static void Main( string[] args )
        {

            string a = null;
            Console.WriteLine( a.MyIsNullOrEmpty() ? "Null Or Empty" : "Not empty" );
            a = "Test";
            Console.WriteLine( a.MyIsNullOrEmpty() ? "Null Or Empty" : "Not empty" );
            Console.ReadKey();
        }
    }
}

, , ++ " ", #. , .

+8

I do not think you can. Extension methods are just syntactic sugar converted to static methods by the compiler.

-2
source

Source: https://habr.com/ru/post/1710456/


All Articles