Rationale behind constraining default parameters as compile-time constants

╄→尐↘猪︶ㄣ 提交于 2021-01-28 21:02:49

问题


I am wondering why this would not compile:

public static void SomeFunction(Guid someGuid = Guid.NewGuid())
{
        // Do stuff
}

with the message

"Default parameter value for 'someGuid' must be a compile-time constant"

while the overloaded version would compile:

    public static void SomeFunction()
    {
        SomeFunction(Guid.NewGuid());
    }

    public static void SomeFunction(Guid someGuid)
    {
        // Do stuff
    }

In other words, why doesn't the compiler translate the first situation in the second? What lies behind this design choice?


回答1:


Default parameter values are compiled to CIL metadata (like attributes) which can only hold literal values.

The C# compiler does some magic there to allow decimals as well.



来源:https://stackoverflow.com/questions/13731814/rationale-behind-constraining-default-parameters-as-compile-time-constants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!