问题
As far as I know, interfaces cannot be instantiated.
If this is true, why does the below code compile and execute? It allows you to create a variable interface. Why is this possible?
Interface:
public interface IDynamicCode<out TCodeOut>
{
object DynamicClassInstance { get; set; }
TCodeOut Execute(string value = "");
}
InCode:
var x = new IDynamicCode<string>[10];
Result:
UPDATE:
It only happens when array declared. Not a single instance.
回答1:
You're not instantiating an interface, but an array of that interface.
You can assign an instance of any class that implements IDynamicCode<string>
to that array. Say you have public class Foo : IDynamicCode<string> { }
, you can instantiate that and assign it to an element of that array:
var x = new IDynamicCode<string>[10];
x[5] = new Foo();
Instantiating the interface would not compile:
var bar = new IDynamicCode<string>();
回答2:
You're not creating an instance of the interface; you're creating an array which can hold a number of objects which conform to IDynamicCode
. Initially, the entries have their default value, which is null
.
回答3:
this is not creating an interface variable
this will create an array where each element implements the interface. if you write x[0] = new IDynamicCode<string>();
then you will get the error. all of the elements are null
, so you need to assign each element an object which implements IDynamicCode
回答4:
Just an interesting side-note:
While not possible conceptually, syntactically it is indeed possible to instantiate an interface under specific circumstances.
.NET has something called a CoClassAttribute which tells the compiler to interpret marked interface as specified concrete type. Using this attribute would make the following code perfectly valid and not throw a compile time error (note that this is not an array as in the original post):
var x = new IDynamicCode<string>();
A typical declaration of such attribute would look like this:
[ComImport]
[Guid("68ADA920-3B74-4978-AD6D-29F12A74E3DB")]
[CoClass(typeof(ConcreteDynamicCode<>))]
public interface IDynamicCode<out TCodeOut>
{
object DynamicClassInstance { get; set; }
TCodeOut Execute(string value = "");
}
Should this attribute be ever used and if, then where? The answer is "mostly never"! However, there are a couple of scenarios specific to COM interop where this will provide to be a useful feature.
More can be read about the topic from the following links:
- Who says you can’t instantiate an interface?
- Is it ok to (ab)use CoClassAttribute to provide a default implementation for an interface
- How does the C# compiler detect COM types?
回答5:
when you call
var x = new IDynamicCode<string>[10];
Constructors are not called. They are only declared.
来源:https://stackoverflow.com/questions/30914076/why-is-interface-variable-instantiation-possible