【问题标题】:C# Method Property ParamC# 方法属性参数
【发布时间】:2017-08-08 09:58:06
【问题描述】:

我想添加一个属性作为参数。

    /// <summary>
    ///     Permet de passer à la prochaine valeur de la <see 
    cref="Dimension" />.
    /// </summary>
    public void DimensionSuivante()
    {
        if (Dimension == enuDimension.Petite)
            Dimension = enuDimension.Maximale;
        else
            Dimension += 1;
    }

    /// <summary>
    ///     Permet de passer à la prochaine valeur de la <see cref="Qualite" 
    />.
    /// </summary>
    public void QualiteSuivante()
    {
        if (Qualite == enuQualite.Faible)
            Qualite = enuQualite.Excellente;
        else
            Qualite += 1;
    }

    /// <summary>
    ///     Permet de passer à la prochaine valeur de la <see 
    cref="Sensibilite" />.
    /// </summary>
    public void SensibiliteSuivante()
    {
        if (Sensibilite == enuSensibilite.ISO_800)
            Sensibilite = enuSensibilite.ISO_64;
        else
            Sensibilite += 1;
    }

这些方法会重复很多,所以我想创建一个新方法,我们将Property 作为parameter 传递。我不知道syntax 会是什么。 我尝试在param 之前添加object。这是我到目前为止的方法。

    private void GetPropertyNext(PropertyName)
    {
        if (PropertyName == FirstOfEnu)
            PropertyName = LastOfEnu;
        else
            PropertyName += 1;
    }

【问题讨论】:

  • 在最后的代码中,您需要在 PropertyName 之后定义变量名。

标签: c# .net visual-studio parameters properties


【解决方案1】:

您不能通过引用传递属性。请参阅How to pass properties by reference in c#?C# Pass a property by reference

但通常情况下,您不需要这样做。这就是这里的情况。我认为你的方法应该更像这样:

static T IncrementEnum<T>(T value)
{
    int[] values = Enum.GetValues(typeof(T)).Cast<int>().ToArray();
    int i = (int)(object)value,
        min = values.Min(),
        max = values.Max();

    return (T)(object)(i == max ? min : i + 1);
}

那么你可以这样称呼它:

Dimension  = IncrementEnum(Dimension);

上面的方法有些开销,因为每次调用它都要确定minmax的值。您可以将其封装在泛型类型中,并在静态构造函数中初始化这些值,如果这会导致性能开销成为问题。

【讨论】:

    猜你喜欢
    • 2014-04-01
    • 2014-07-17
    • 2016-07-13
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 2021-02-05
    • 2019-01-25
    • 1970-01-01
    相关资源
    最近更新 更多