Based on http://msdn.microso开发者_高级运维ft.com/en-us/library/aa288208%28v=vs.71%29.aspx
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).
I have problems to understand Item 2. Can someone give me a concrete example?
Basically, structs do not support inheritance. Although techincally they do inherit from the base class object, item 2 states that you cannot call the base class constructor explicitly. More info here: http://msdn.microsoft.com/en-us/library/aa288471%28v=vs.71%29.aspx
struct
(implicitly) derive immediately from System.ValueType
and the only constructor on that abstract
class is protected
and parameterless. These are facts by the language specification and the statement you are questioning is a consequence of these facts and stated explicitly in the language specification from §11.3.8:
A
struct
instance constructor is not permitted to include a constructor initializer of the formbase(...)
.
For reference types that derive from classes that have an accessible non-parameterless constructor, you can do the following:
class Base {
private readonly string baseName;
public string BaseName { get { return this.baseName; } }
public Base(string baseName) { this.baseName = baseName; }
}
class Derived : Base {
private readonly string derivedName;
public string DerivedName { get { return this.derivedName; } }
public Derived(string baseName, string derivedName) : base(baseName) {
this.derivedName = derivedName;
}
}
The point is that a Derived
is a Base
and as such, a constructor for Base
needs to be invoked to completely initialize the new instance of Derived
(i.e., the parts of Derived
that make it a Base
need to be initialized). Invoking the base constructor through the syntax base(...)
lets you invoke the appropriate constructor.
The statement you are questioning about struct
states that it is not permitted to have such an invocation. This is mostly because there can never be such a constructor per the facts stated in the first sentence of this answer.
Here is an example of an initializer in the form: base (argument-list).
public class Foo
{
public Foo(int i) { Debug.WriteLine(i); }
}
public class Bar: Foo
{
public Bar() : base(4) {} // Prints '4' to debug via the base class's constructor.
}
Structs do not support inheritance, so explicitly calling the base class's constructor is not allowed.
精彩评论