zoukankan      html  css  js  c++  java
  • C#中,接口不能被实例化,但存在特例

    看一个例子:

    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 }
  • 相关阅读:
    Java运算符
    Java数据类型,常量与变量
    内存
    cmd编码
    DELL G7重置电脑操作步骤
    关于es6中...运算符的总结
    js数组与字符串相互转换
    JS中的continue,break,return的区别
    git提交步骤
    数据修改后点击确定没有保存 还是原来的数据
  • 原文地址:https://www.cnblogs.com/submarinex/p/3214756.html
Copyright © 2011-2022 走看看