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中常见的控件的使用
相关推荐
for_ever_love__6 小时前
UI学习:UISearchController基础了解和应用
学习·ui·ios·objective-c
心中有国也有家6 小时前
GE图引擎深度解析——CANN的计算图优化与执行引擎
人工智能·pytorch·python·学习·numpy
isyangli_blog7 小时前
OpenDayLight (Carbon 版本) 启动与组件安装
开发语言·php
vb2008117 小时前
FastAPI APIRouter
开发语言·python
Benszen7 小时前
KVM虚拟化解决方案
开发语言·perl
会编程的土豆7 小时前
Go 语言反射(Reflection)详解
开发语言·后端·golang
東雪木7 小时前
多线程与并发编程 专属复习笔记
java·开发语言·笔记·java面试
GHL2842710907 小时前
换脸工作流学习
学习·ai
_李小白8 小时前
【android opencv学习笔记】Day 28: 滤波算法之中值滤波器
android·opencv·学习
杨充8 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法