多个返回值到对象属性中

时间:2017-10-03 20:09:23

标签: c#

我已多次阅读the article about multiple returns。但是,当我试图获取的值不被破坏成简单的标量,而是被破坏为对象属性时,我无法弄清楚如何应用它。 (如果需要,我可以使用C#V7。)

当参数是对象属性时,也不允许使用out关键字。那么我该怎么做这个例子:

Tools.orientation(ent.esr, out e.heading, out e.pitch, out e.roll);

//...

public static void orientation(EntityStateRepository esr, out double  heading, out double pitch, out double roll)
{
    TaitBryan topoEuler = topoToGeoc.eulerTrans(esr.worldOrienation);
    heading = MathHelper.RadiansToDegrees(topoEuler.psi);
    pitch = MathHelper.RadiansToDegrees(topoEuler.theta);
    roll = MathHelper.RadiansToDegrees(topoEuler.phi);
}

3 个答案:

答案 0 :(得分:3)

我认为你在想这个。使用这些属性定义新类型并返回该类型的实例。例如:

public static OrientationModel orientation(EntityStateRepository esr)
{
    TaitBryan topoEuler = topoToGeoc.eulerTrans(esr.worldOrienation);
    var container = new OrientationModel();

    container.heading = MathHelper.RadiansToDegrees(topoEuler.psi);
    container.pitch = MathHelper.RadiansToDegrees(topoEuler.theta);
    container.roll = MathHelper.RadiansToDegrees(topoEuler.phi);

    return container;
}

public sealed class OrientationModel {
    public decimal heading {get;set;}
    public decimal pitch {get;set;}
    public decimal roll {get;set;}
}

答案 1 :(得分:2)

您无法通过引用传递属性,因此最好的方法是传入父对象:

Tools.orientation(ent.esr, e);

//...

public static void orientation(EntityStateRepository esr, TypeOfE e)
{
    TaitBryan topoEuler = topoToGeoc.eulerTrans(esr.worldOrienation);
    e.heading = MathHelper.RadiansToDegrees(topoEuler.psi);
    e.pitch = MathHelper.RadiansToDegrees(topoEuler.theta);
    e.roll = MathHelper.RadiansToDegrees(topoEuler.phi);
}

或者,如果您希望保留带有out参数的版本并添加重载:

public static void orientation(EntityStateRepository esr, TypeOfE e)
{
    double heading;
    double pitch;
    double roll;
    Tools.orientation(ent.esr, out heading, out pitch, out roll);
    e.heading = heading;
    e.pitch = pitch;
    e.roll = roll;
}
//...

public static void orientation(EntityStateRepository esr, out double  heading, out double pitch, out double roll)
{
    TaitBryan topoEuler = topoToGeoc.eulerTrans(esr.worldOrienation);
    heading = MathHelper.RadiansToDegrees(topoEuler.psi);
    pitch = MathHelper.RadiansToDegrees(topoEuler.theta);
    roll = MathHelper.RadiansToDegrees(topoEuler.phi);
}

答案 2 :(得分:2)

为了完整起见,您提到了多种返回类型。

使用C#7功能和NuGet包System.ValueTuple,您可以编写以下内容,它等同于Igor的回答,除非您要重用{{1 } class

SomeContainer

使用

访问
public static (double heading, double pitch, double roll) orientation(EntityStateRepository esr)
{
    TaitBryan topoEuler = topoToGeoc.eulerTrans(esr.worldOrienation);

    var h = MathHelper.RadiansToDegrees(topoEuler.psi);
    var p = MathHelper.RadiansToDegrees(topoEuler.theta);
    var r = MathHelper.RadiansToDegrees(topoEuler.phi);

    return (h, p, r);
}