C#(3):类、对象、类成员
类是对现实世界抽象所得到的结果,事务包括物质和运动(实体和逻辑)。
对象是类经过实例化得到的内存中的实体。
实例化:将一系列类聚合成的实体。
实例化就是说明对象属于哪个类,说明完就可以调用函数了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ClassAndInstance
{
class Program
{
static void Main(string[] args)
{
Form myForm;//声明myform对象
myForm=new Form();//myform对象引用form实例
myForm.Text = "myform";
myForm.ShowDialog();
}
}
}
类属性测试代码,组内调数据时调用的cache的webservice接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PropertySample
{
class Program
{
static void Main(string[] args)
{
AdventureWorkLT2012Entities proxy=new AdventureWorkLT2012Entities;//创建链接实例
foreach (product p in proxy.Products){
Console.WriteLine(p.name);
}
}
}
}
类方法测试代码,最常用的算法结构使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MethodSample
{
class Program
{
static void Main(string[] args)
{
double x = Math.Sqrt(4);//调用math对象的方法
Console.WriteLine(x);
}
}
}
类事件测试代码,侧重于静态对象
tiemspan:system的函数,表示一个时间间隔。
FromSeconds:返回表示指定秒数的 TimeSpan,其中对秒数的指定精确到最接近的毫秒
Interval:timer的属性,timespan获取或设置计时器刻度之间的时间段
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;//引用多线程
namespace EventSample
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();//实例化时钟
timer.Interval = TimeSpan.FromSeconds(1); //间隔多长时间触发一次时间
timer.Tick += timer_Tick;
timer.Start();//启动计时器
}
void timer_Tick(object sender, EventArgs e) //事件处理器,对tick触发的事件进行执行
{
this.TimeTextBox.Text = DateTime.Now.ToString();//调用前端的文本框显示当前时间并转为string类型
}
}
}
静态与非静态方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace StaticSample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello");//静态方法
Form form = new Form();
form.Text = "hello";//访问实例属性
form.ShowDialog();//访问实例的方法
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现