You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中new()与new class()的区别及差异输出示例咨询

C#中new()和new 类名()的区别

核心差异

  • new 类名():显式指定要实例化的类型,编译器直接创建该类的实例,结果不受左侧变量或上下文目标类型的影响。
  • new():是C# 9.0引入的目标类型推断语法,编译器会根据左侧变量的类型(或上下文明确的目标类型)自动推断要实例化的类型,必须有清晰的目标类型才能使用。

你给出的示例无差异的原因

在Human John = new();代码中,左侧变量John的类型明确为Human,编译器会自动推断new()等价于new Human(),因此运行效果完全一致。

二者执行结果不同的示例

当目标类型为父类,且存在继承它的子类时,new()会创建父类实例,而显式指定子类的new 子类()会创建子类实例,此时行为差异明显:

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}

// 测试代码
Animal pet1 = new Dog();
pet1.MakeSound(); // 输出:Woof!

Animal pet2 = new();
pet2.MakeSound(); // 输出:Animal sound

内容的提问来源于stack exchange,提问作者Dane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 20:07:37