Unintuitive behaviour with struct initialization and default arguments

后端 未结 5 1730
半阙折子戏
半阙折子戏 2021-02-12 17:46
public struct Test 
{
    public double Val;
    public Test(double val = double.NaN) { Val = val; }
    public bool IsValid { get { return !double.IsNaN(Val); } }
}

Te         


        
5条回答
  •  眼角桃花
    2021-02-12 18:38

    I suspect this is because a default constructor with no parameters is not allowed in c# so when you call the constructor Test without parameters it just initialises them as usual. Check this post for more details (not quite a duplicate): Why can't I define a default constructor for a struct in .NET?

提交回复
热议问题