简体   繁体   中英

In C++ it's a member variable that is a reference to a struct. What's the C# equivalent?

I'm new to C#. The following code is how I would achieve what I want in C++. I have reasons that the struct needs to be a struct (and mutable).

What would the C# equivalent of the following code be?

struct SomeStruct {
    int a;
    int b;
};

class SomeClass {
public:
    SomeStruct& target;

public:
    SomeClass(SomeStruct &t) :
        target(t)
    {
    }
};

I want to be able to use instances of SomeClass to mutate the underlying struct. I have seen this question but in my case the target is a struct.

This is not possible for struct fields. You can only get a reference to a boxed struct in C# (ie a separately allocated struct), and this practically cancels any benefits of using a struct in the first place.

Since structs are passed around by value (eg copied from function parameters into local variables), passing around pointers to struct fields would mean you would easily get pointers to out-of-scope data.

C# was deliberately designed to avoid stuff like this:

// not real C# code
void SomeMethod()
{
    SomeStruct *ptr = GetStructPointer();

    // <-- what does ptr point to at this point?
}

SomeStruct* GetStructPointer()
{
    SomeStruct local;
    return &local;
}

It would be ref SomeStruct t param. See MSDN documentation for the ref C# keyword https://msdn.microsoft.com/en-us/library/14akc2c7.aspx .

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