3 回答
TA贡献1906条经验 获得超10个赞
您的大多数类声明都无法编译。只有B,D和Gcompile的声明。
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
TA贡献1817条经验 获得超6个赞
abstract不能实例化一个类。
所述sealed改性剂防止被继承的类和abstract改性剂需要被继承的类。
来源:https : //docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract
接口不能直接实例化。
来源:https : //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/
这意味着:
class Program
{
static void Main(string[] args)
{
A a = new A(); // ERROR: cannot instantiate interface
B b = new B(); // OK
A ab = new B(); // ERROR: class B doesn't implement interface A
B ba = new A(); // ERROR: cannot instantiate interface
C c = new C(); // ERROR: cannot instantiate abstract class
D d = new D(); // OK
E e = new E(); // OK
F af = new A(); // ERROR: cannot instantiate interface
A fa = new F(); // OK: class F does implement interface A
G g = new G(); // OK
}
}
TA贡献1834条经验 获得超8个赞
您不能新建接口或抽象类,因此会导致错误。
接口只是合约。他们不是班级。你不能实例化它们。
抽象类只能被继承。它们不能自己创建。
密封类只是意味着它们不能被继承。您仍然可以实例化它们。
- 3 回答
- 0 关注
- 157 浏览
添加回答
举报
