C# 对象创建与方法调用示例
下面是一个 C# 代码示例,创建两个对象并调用方法:
using System;
class Person
{
private string name;
private int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public void SayHello()
{
Console.WriteLine('Hello, my name is ' + name + ' and I am ' + age + ' years old.');
}
}
class Program
{
static void Main(string[] args)
{
// 创建两个 Person 对象
Person p1 = new Person("Alice", 25);
Person p2 = new Person("Bob", 30);
// 调用方法
p1.SayHello();
p2.SayHello();
Console.ReadKey();
}
}
输出结果:
Hello, my name is Alice and I am 25 years old.
Hello, my name is Bob and I am 30 years old.
原文地址: https://www.cveoy.top/t/topic/nrPZ 著作权归作者所有。请勿转载和采集!