C#从零开始学习(基本语法概念)(2)

深入C#

本章所有的代码都放在
https://github.com/hikinazimi/head-first-Csharp

控制台项目结构

每个C#程序采用同样的方式组织,命名空间,类和方法

csharp 复制代码
using System;

namespace helloworld//命名空间
{
    class Program//类
    {
        static void Main(string[] args)//程序入口
        {
            Console.WriteLine("Hello World!");
        }
    }
}

常见语法

  1. 变量声明
csharp 复制代码
int height;
bool flag;
string message = "zzz";
  1. 操作符
csharp 复制代码
int width = 3;
width++;
string result = "The";
result = result + "area";
  1. 条件
csharp 复制代码
int height = 10;
string message = ""'
if(height==5)
{
	message = "height is 5";
}
  1. 循环
csharp 复制代码
while()
{
}
do
{
}while();

for(int i=0;i<10;i++)
{
}

控制驱动用户界面的机制

介绍了文本框,单选钮,列表框,组合框,通过这些框输入数据,显示在界面上

创捷一个WPF应用来试验控件

设置Grid创建一个三行两列的框架

xml 复制代码
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition Height=".5*"/>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

    </Grid>

添加一个textBox控件

点击工具箱中textBox,并设置对应参数

增加一个事件处理器只允许输入数字

在textBox中PreviewTextInput中增添一个函数

对应函数填写如下代码

csharp 复制代码
        private void numberTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = !int.TryParse(e.Text, out int result);
        }

用户在textBox中输入文本时,在更新前,会先调用这个函数

combox的使用

xml 复制代码
        <ListBox x:Name="myListBox" Grid.Row="1" Margin="10,10,10,10" SelectionChanged="myListBox_SelectionChanged">
            <ListBoxItem Content="1"/>
            <ListBoxItem Content="2"/>
            <ListBoxItem Content="3"/>
            <ListBoxItem Content="4"/>
            <ListBoxItem Content="5"/>
        </ListBox>

这是一个下拉选择框

C#逻辑代码,通过判断选择的数字,将其赋值给number

csharp 复制代码
        private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (myListBox.SelectedItem is ListBoxItem listBoxItem)
            {
                number.Text = listBoxItem.Content.ToString();
            }
        }

最终效果如下图所示,在不同的模块输入不同的数字,会同步在右边显现

至此,我们就学习完了第二章,然后让我们复习一下本章讲了什么

  • 学习了C#常见的语法如变量声明,操作符,条件判断和循环语句
  • 学习了WPF中常见的控件的使用
相关推荐
weixin_440730502 分钟前
字符编码笔记-utf-8 、unicode、gbk,ascii编码格式
开发语言·笔记
励志不掉头发的内向程序员1 小时前
【从零写一个CAD 03】三个 double 值得单独一个类吗:把视图变换抽成 View
开发语言·c++·qt·学习·系统架构
PHP实战开发录1 小时前
PHP接口大整数为什么变了
开发语言·php
临床数据科学和人工智能兴趣组5 小时前
在R语言中, 使用 as.factor() 函数转换数值型变量
开发语言·r语言
m4Rk_8 小时前
【论文阅读】Agent 记忆机制(83):Inside Out——用可演化 PersonaTree 构建 Agent 的核心长期记忆
论文阅读·人工智能·学习·开源·github
andyweike8 小时前
php笔记
开发语言·笔记·php
鬓戈8 小时前
Rust 语言与 AI 应用生态调研及学习路径
人工智能·学习·rust
传奇开心果编程9 小时前
【SwiftUI娓娓道来】第3课:让界面活起来——交互与动画指南
学习·macos·ui·ios·swiftui·swift
Circ.9 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
xian_wwq9 小时前
【学习笔记】等保合规安全基线核查实战
笔记·学习