简体   繁体   中英

C# create version of struct (inheritance or otherwise) that has fields renamed

Let's say I have a C# struct of which I want to create a derived version that is functionally equivalent but has some Properties or Functions renamed. How would I best do that to have the derived version not perform any worse and avoiding code duplication in the process?

To be more specific, I have a struct Vector3 with properties X, Y, Z and plenty of functions and want to have a structLlaVec with the names of the properties changed to Longitude, Latitude and Altitude, potentially also the documentation of these properties changed.

Is there any way other than duplicating the implementation of the struct to do this?

Don't use inheritance but use encapsulation.

In other words, create a new type that wraps the struct you have and delegate your new functions or properties to the properties of the wrapped struct.

For instance:

struct LlaVec
{
    private readonly Vector3 _v;

    public LlaVec( Vector3 v ) 
    {
        _v = v;
    }

    public int Altitude { get { return _v.Z; }}
}

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