C# Struct No Parameterless Constructor? See what I need to accomplish

前端 未结 6 573
既然无缘
既然无缘 2020-12-15 08:06

I am using a struct to pass to an unmanaged DLL as so -

[StructLayout(LayoutKind.Sequential)]
        public struct valTable
        {
            public byt         


        
6条回答
  •  天命终不由人
    2020-12-15 08:46

    Struct constructors are similar to class constructors, except for the following differences:

    • Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
    • A struct cannot have an initializer in the form: base (argument-list).

    This means that

    A default(parameterless) constructor for a struct could set different
    values than the all-zeroed state which would be unexpected behavior. The
    .Net Runtime therefore prohabits default constructors for struct.
    

    The typical way to get around this scenario is to create a static method that will create your new instance, initialize it the way you want, and return it. This is the way it is done in .NET to get structures initialized with specific values.


    ref; Structs cannot contain explicit parameterless constructors. WHY?

提交回复
热议问题