C#中不能通过new关键字创建实例的情况

  1. 抽象类(abstract)
cs 复制代码
public abstract class AbstractClass 
{
    // 不能直接new
    // AbstractClass obj = new AbstractClass(); // 编译错误
}
  1. 接口(interface)
cs 复制代码
public interface IMyInterface 
{
    // 不能直接new
    // IMyInterface obj = new IMyInterface(); // 编译错误
}

###实现接口的类可以通过new创建实例
// 实现接口的类
public class MyClass : IMyInterface 
{
    public void SomeMethod() { }
}

// 正确使用方式
IMyInterface obj = new MyClass(); // 通过实现接口的类创建实例
  1. 静态类
cs 复制代码
public static class StaticClass 
{
    // 不能new静态类
    // StaticClass obj = new StaticClass(); // 编译错误
}
  1. 带私有构造函数且没有提供创建实例方法的类
cs 复制代码
public class PrivateConstructorClass 
{
    // 私有构造函数
    private PrivateConstructorClass() {}

    // 没有提供创建实例的方法
    // PrivateConstructorClass obj = new PrivateConstructorClass(); // 编译错误
}
  1. 未指定具体类型的泛型类
cs 复制代码
public class GenericClass<T> 
{
    // 不能直接new泛型类型T
    // T instance = new T(); // 编译错误(除非T有无参构造函数)
}
  1. 没有无参构造函数的类(如果要求必须使用特定参数的构造函数)
cs 复制代码
public class ClassWithOnlyParameterizedConstructor 
{
    // 只有带参数的构造函数
    public ClassWithOnlyParameterizedConstructor(int x) {}

    // ClassWithOnlyParameterizedConstructor obj = new ClassWithOnlyParameterizedConstructor(); // 编译错误
}

注意:

  • 抽象类、接口、静态类是最典型的不能new的类型

  • 私有构造函数的类需要看是否提供了创建实例的方法

  • 泛型类的实例化依赖于具体的类型参数

相关推荐
唐青枫1 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech2 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf3 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6253 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech3 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
2601_962072554 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
m0_547486664 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
叶帆4 天前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#
IT方大同4 天前
(嵌入式操作系统)信号量
嵌入式硬件·c#
z落落4 天前
C# FileStream文件流读取文件
开发语言·c#