控制台之匿名类,类部分,常量,构造函数等

本文通过具体示例介绍了如何在C#中实现面向对象编程,包括创建Person类以跟踪对象实例数量,以及采用面向对象方法计算两点间距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建控制台

类的封装、分开写类、静态、常量、构造函数,还有类的实例化。

1创建Person类并添加相应的字段与方法和构造函数,并且有num字段能够记录这个类生生成了多少个具体的对象。

2分别使用面向过程的方法和面向对象的方法,完成如下命题:求 两点之间的距离。

开始时间:2012年09月3日 星期一 11:40
截止时间:2012年09月 10日 星期一 11:40
最近编辑:2012年09月3日 星期一 16:03 (337单词)
已经保存了您的修改

1、

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _9._3
{
class Program
{
static void Main(string[] args)
{
Person a = new Person();
Console.WriteLine("name:"+a.Name+" age:"+a.Age);
a.jishu();
Console.ReadKey();
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _9._3
{
class Person
{
string name;
public string Name
{
get { return name; }
}
int age;
public int Age
{
get { return age; }
}
public static int num;
public Person()
{
name = "匿名";
age = 0;
num++;
}
public Person(string name, int age)
{
this.name = name;
this.age = age;
num++;
}
public void jishu()
{
Console.WriteLine(num);
}
}
}

2、

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _09._03
{
class Program
{
static void Main(string[] args)
{
int x1=-1, x2, y1=-1, y2;
x2 = int.Parse(Console.ReadLine());
y2 = int.Parse(Console.ReadLine());
double h1 = Math.Sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
Console.WriteLine(h1);
Class1 a = new Class1();
Class1 b = new Class1(x2,y2);
Console.WriteLine(a.jishu(b));
Console.ReadKey();
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _09._03
{
class Class1
{
int x, y;
public Class1()
{
x = -1;
y = -1;
}
public Class1(int x,int y)
{
this.x = x;
this.y = y;
}
public double jishu(Class1 p)
{
return Math.Sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
}
}
}

匿名类和类的分开写

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _3
{
class Program
{
static void Main(string[] args)
{
var a = new { Naem = "靠", Age = 23 };
//匿名类
Console.WriteLine("Name:"+a.Naem+" Age:"+a.Age);
Class1 b = new Class1();
b.ab();
Console.ReadKey();
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _3
{
partial class Class1
{
int a;
int b;
public Class1()
{
a = 1;
b = 2;
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _3
{
partial class Class1
{
public void ab()
{
Console.WriteLine(a + b);
}
}
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值