Unintuitive behaviour with struct initialization and default arguments

后端 未结 5 2299
小鲜肉
小鲜肉 2021-02-12 17:52
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:47

    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?

提交回复
热议问题