【问题标题】:Can a method determine at run-time if a parameter has been defaulted? [duplicate]方法能否在运行时确定参数是否已默认? [复制]
【发布时间】:2019-02-21 13:41:02
【问题描述】:

鉴于此示例代码,方法 foo 是否可以在运行时确定第 4 个参数已被默认?

using System;

namespace DefaultParameters {
    class Program {
        static void Main(string[] args) {
            int a = 0,b = 1,c = 3;
            foo(a, b, c);       // The 4th parm is defaulted in the method definition.
            foo(a, b, c, 100);  // The 4th parm is explicit in the method call.
        }

        /// <summary>
        /// A method with a default paramater
        /// </summary>
        /// <param name="speed">Speed</param>
        /// <param name="brightness">Brightness</param>
        /// <param name="weight">Weight</param>
        /// <param name="humidity">Humidity</param>
        public static void foo(int speed, int brightness, int weight, int humidity = 42) {
            Console.WriteLine("speed = " + speed + " brightness = " + brightness + " weight = " + weight + " humidity  = " + humidity);
        }
    }
}

【问题讨论】:

  • 更好的solution 是像第一个答案那样重载方法。

标签: c# methods optional-parameters


【解决方案1】:

没有

您可以随意猜测,如果它默认值,则可能没有给出,但无法确定。

【讨论】:

    猜你喜欢
    • 2012-07-15
    • 2016-05-27
    • 2015-08-20
    • 2020-01-27
    • 2012-12-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多