首页 > 解决方案 > 如果在 C# 中是密封的、继承的或抽象的,如何知道是否可以实例化一个类或接口?

问题描述

我很难知道可以在Main方法中实例化以下哪些类/接口(哪个类/接口完全可以)。对于某些类和接口,代码如下所示:

interface A {public void Method();}
class B {public static int b;}
abstract class C:B {public void Method1();}
sealed class D:B {} ;
class E:A {};
class F:A {public void Method();}
class G:C {};

然后稍后,我们在另一个类中有 Main 方法,就像这样......

class Program 
{
    static void Main(string[] args) 
    {
        A a = new A();
        B b = new B();
        A ab = new B();
        B ba = new A();
        C c = new C();
        D d = new D();
        E e = new E();
        F af = new A();
        A fa = new F();
        G g = new G();
    }
}

那么,我们可以从上面使用哪些?我知道这是一个愚蠢的问题,但这是我们在大学考试中实际得到的结果。

标签: c#classinstanceabstractsealed

解决方案


您的大多数类声明都无法编译。只有B,DGcompile 的声明。

interface A {public void Method();} // "public" cannot be used on interface members
class B {public static int b;}
abstract class C:B {public void Method1();} // method without body should be marked as "abstract"
sealed class D:B {} ;
class E:A {}; // interface methods not implemented
class F:A {public void Method();} // method does not have a body
class G:C {};

对于 中的语句,它们中的Main大多数也不编译:

A a = new A(); // cannot instantiate interface A
B b = new B(); // OK because B is a normal class
A ab = new B(); // B can be instantiated for aforementioned reasons, but cannot be
                // assigned to A because they are unrelated types
B ba = new A(); // cannot instantiate interface A. A also cannot be assigned to
                // B because they are unrelated.
C c = new C(); // cannot instantiate abstract class C
D d = new D(); // OK, D is a normal class. It is sealed, but that just means no 
               // class can derive from it, nothing to do with instantiation
E e = new E(); // OK, E is a normal class
F af = new A(); // cannot instantiate interface A
A fa = new F(); // F is a normal class, and is assignable to A because F implements A
G g = new G(); // OK, G is a normal class

一般模式:

  • 抽象类和接口不能被实例化
  • 关键字与实例化sealed无关
  • 只有私有构造函数的类不能被实例化
  • 如果满足以下条件,则可以将 T1 类型的表达式分配给 T2 类型的变量:
    • T1和T2是同一类型,或;
    • T1 继承 T2,或者;
    • T1 实现 T2,或者;
    • T1 可隐式转换为 T2

推荐阅读