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 關注
- 154 瀏覽
添加回答
舉報
