C#中,接口不能被实例化,但存在特例
2013-11-21 09:53
218 查看
http://www.cnblogs.com/submarine/archive/2013/07/25/3214756.html
看一个例子:
则
将会报错:接口不能被实例化。
如果:
1 class Foo : IFoo
2 {
3 readonly string name;
4 public Foo(string name)
5 {
6 this.name = name;
7 }
8 string IFoo.Message
9 {
10 get
11 {
12 return "Hello from " + name;
13 }
14 }
15 }
则
就不会有问题。
MSDN中提到:
An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface.
接口不能被直接实例化。它的成员通过实现该接口的任何类或者结构来实现。
存在的一个例外就是,该接口如果是一个COM 接口,则可以被实例化,看这篇博文Who says you can’t instantiate an interface?:
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 IFoo obj = new IFoo("abd");
6 }
7 }
8
9 // these attributes make it work
10 // (the guid is purely random)
11 [ComImport, CoClass(typeof(Foo))]
12 [Guid("d60908eb-fd5a-4d3c-9392-8646fcd1edce")]
13 interface IFoo
14 {
15 string Message { get; }
16 }
17
18 class Foo : IFoo
19 {
20 readonly string name;
21 public Foo(string name)
22 {
23 this.name = name;
24 }
25 string IFoo.Message
26 {
27 get
28 {
29 return "Hello from " + name;
30 }
31 }
32 }
看一个例子:
1 interface IFoo 2 { 3 string Message { get; } 4 }
则
1 IFoo obj = new IFoo("abd");
将会报错:接口不能被实例化。
如果:
1 class Foo : IFoo
2 {
3 readonly string name;
4 public Foo(string name)
5 {
6 this.name = name;
7 }
8 string IFoo.Message
9 {
10 get
11 {
12 return "Hello from " + name;
13 }
14 }
15 }
则
1 IFoo obj = new Foo("abd");
就不会有问题。
MSDN中提到:
An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface.
接口不能被直接实例化。它的成员通过实现该接口的任何类或者结构来实现。
存在的一个例外就是,该接口如果是一个COM 接口,则可以被实例化,看这篇博文Who says you can’t instantiate an interface?:
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 IFoo obj = new IFoo("abd");
6 }
7 }
8
9 // these attributes make it work
10 // (the guid is purely random)
11 [ComImport, CoClass(typeof(Foo))]
12 [Guid("d60908eb-fd5a-4d3c-9392-8646fcd1edce")]
13 interface IFoo
14 {
15 string Message { get; }
16 }
17
18 class Foo : IFoo
19 {
20 readonly string name;
21 public Foo(string name)
22 {
23 this.name = name;
24 }
25 string IFoo.Message
26 {
27 get
28 {
29 return "Hello from " + name;
30 }
31 }
32 }
相关文章推荐
- C#中,接口不能被实例化,但存在特例
- 接口和抽象类不能实例化对象
- C# 为什么用接口实例化一个实现该接口的类?
- c#中 接口成员为什么不能使用关键字static virtul override abstract
- java 为什么接口不能实例化
- C#读写EXCEL源码提示“office检测到此文件存在一个问题。为帮助保护您的计算机,不能打开此文件。 ”的解决
- 接口真的不能被实例化?
- 【Vegas原创】C#不能多重继承,怎么办?接口!
- java接口不能实例化原因浅谈
- C# 接口不能完善的事
- JavaSE8基础 接口不能直接实例化
- 为什么在网页链接中存在#号不能正常链接?????,如链接到"http://www.ho.com/c#.html"
- java的接口不能实例化,但是有些函数可以这样写
- C#接口介绍-接口为什么不能使用委托
- C# 实例化接口对象的方法
- C#中接口声明属性,但是提示“接口”中不能有属性。
- java的接口为什么不能实例化
- 为什么C#中显示接口不能加访问修饰符
- 【Vegas原创】C#不能多重继承,怎么办?接口!
- C#不能被继承和不能被实例化的类