简体   繁体   中英

C++/CLI and C#: object returns itself

Given a class Object , it's possible in C++ to return a reference to the object itself like:

    //C++
    class Object
    {
        Object& method1()
        {
            //..
            return *this;
        }
        Object& method2()
        {
            //.
            return *this;
        }
    }

And then consume it as:

    //C++
    Object obj;
    obj.method1().method2();

Is it possible to achive the same effect in C++/CLI and use it in C# application? I've tried the following (with refs % and handles ^ ), which compiles in C++/CLI, but C# says that such methods are

is not supported by the language

    //C++/CLI - compiles OK
    public ref class Object
    {
        Object% method1()
        {
            //..
            return *this;
        }
        Object% method2()
        {
            //.
            return *this;
        }
    }

Then use as:

    //C#
    Object obj = new Object();
    obj.method1(); //ERROR
    obj.method1().method2(); //ERROR

Thanks

You just need the following for C++/CLI:

public ref class Object
{
public:
    Object ^method1()
    {
        //..
        return this;
    }
    Object ^method2()
    {
        //.
        return this;
    }
};

OK, this worked fine:

//C++/CLI - compiles OK
public ref class Object
{
    Object^ method1()
    {
        //..
        return this;
    }
    Object^ method2()
    {
        //.
        return this;
    }
}

Then use as:

//C#
Object obj = new Object();
obj.method1();
obj.method1().method2();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM