c# 创建对象有哪些方法
2025-01-27 15:45 钟铧若岩 阅读(40) 评论(0) 编辑 收藏 举报1. 使用 new
关键字
示例
// 定义一个简单的类 class Person { public string Name; public int Age; // 构造函数 public Person(string name, int age) { Name = name; Age = age; } } class Program { static void Main() { // 使用 new 关键字创建 Person 对象 Person person = new Person("John", 30); } }
2. 使用对象初始化器
示例
class Car { public string Brand; public string Model; } class Program { static void Main() { // 使用对象初始化器创建 Car 对象 Car car = new Car { Brand = "Toyota", Model = "Corolla" }; } }
3. 使用集合初始化器
示例
using System.Collections.Generic; class Program { static void Main() { // 使用集合初始化器创建 List<int> 对象 List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; } }
4. 使用 Activator.CreateInstance
方法
示例
class Animal { public void Speak() { Console.WriteLine("Animal speaks."); } } class Program { static void Main() { // 使用 Activator.CreateInstance 创建 Animal 对象 Animal animal = (Animal)Activator.CreateInstance(typeof(Animal)); animal.Speak(); } }
5. 使用工厂方法
示例
// 定义一个接口 interface IProduct { void DoSomething(); } // 实现接口的具体类 class ConcreteProduct : IProduct { public void DoSomething() { Console.WriteLine("ConcreteProduct is doing something."); } } // 工厂类 class ProductFactory { public static IProduct CreateProduct() { return new ConcreteProduct(); } } class Program { static void Main() { // 使用工厂方法创建对象 IProduct product = ProductFactory.CreateProduct(); product.DoSomething(); } }
6. 使用克隆(ICloneable
接口)
示例
using System; class MyClass : ICloneable { public int Value; public object Clone() { return new MyClass { Value = this.Value }; } } class Program { static void Main() { MyClass original = new MyClass { Value = 10 }; // 使用克隆方法创建对象副本 MyClass clone = (MyClass)original.Clone(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?