首页 > 编程语言 >C# 基础

C# 基础

时间:2024-09-04 17:48:49浏览次数:1  
标签:PrintCollections C# void 基础 Queue queue1 dict public

using System;

C# CLass


// 成员变量

partial class Human
{

    public const int MaxAge = 200;
    public static bool canFly = false;
    int age;
    public string name;

    public void SetAge(int value)
    {
        this.age = value; // 实例
    }
    public static void SetAge(Human _this, int value) // 静态方法使用成员变量
    {
        _this.age = value;
    }

    public static void PrintTypeName()
    {
        Console.WriteLine("TypeName Human");

    }
}




// 属性

partial class Human
{

    public const int MaxAge = 200;
    public static bool canFly = false;
    int age;
    public string name;

    public int tel { get; set; }
    // 属性Property,使用起来像变量的函数,get,set;

    public int adder
    {
        get
        {
            return adder.value
    }; set
        {
            age -= value
    };
    }

    public void SetAge(int value)
    {
        this.age = value; // 实例
    }
    public static void SetAge(Human _this, int value) // 静态方法使用成员变量
    {
        _this.age = value;
    }

    public static void PrintTypeName()
    {
        Console.WriteLine("TypeName Human");

    }
}
Human h1 = new Human();
h1.adder = "asdasdasd";
string addd = h1.adder
// 属性Property,使用起来像变量的函数,get,set;

在C#中的访问修饰符:

访问修饰符 描述
public 外部可访问。
private 只能在所属类的内部访问。
protected 可以在所属类内部以及派生类(子类)中访问。
internal 在同一程序集内可以访问。
protected internal 在同一程序集内可访问,在派生类中即使在不同程序集也可访问。

在 C#中,常见的类成员状态标识符有以下几种:

状态标识符 描述
static 静态成员属于类本身而不是类的实例,可通过类名直接访问。
const 常量,在编译时确定其值,不能被修改。
readonly 只读成员,只能在声明时或构造函数中赋值。

Q readonly 与 const 的区别是什么?

const

const由于其值在编译时确定,适用于定义一些固定的、不会改变的值,如数学常量(如const double Pi = 3.14159)或一些在程序中始终不变的配置值。因为值在编译时已知,所以在代码中使用const常量时,编译器会直接将常量的值替换到代码中,这可以提高性能。但是,由于其值不能在运行时改变,所以在一些需要根据不同情况确定值的场景下就不适用。

readonly

readonly更加灵活,因为其值可以在运行时根据不同的条件进行初始化。用于一些在对象创建时确定但之后不能改变的值,例如配置文件中的值在程序启动时读取并赋值给readonly字段,或者根据构造函数的参数来确定readonly字段的值。在需要在不同的对象之间保持相同的只读值,但又不能在编译时确定其值的情况下,readonly是更好的选择。

  • Struct默认继承自object,class如果没有明确指出继承自某个类型,那么其默认继承自object
  • Interface:声明我是一个什么样子的类型,不实现
  • Struct 不能继承struct 或者class, 但可以继承接口
  • Class只能继承一个或零个基类,但能继承任意多个接口
  • Abstrct:不能实例化,可以暂时不实现接口,等待子类的实现
  • 父类变量可以存储子类的变量(地址),但不能反过来。
    • 潜在意思,因为子类B是一个父类A
    • 比如A是Human,B是Teacher,学生是人,但人不一定都是老师

泛型

泛型允许您定义类型安全的数据结构, 而不需要提前指定具体的数据类型。
使用占位符(通常是T)来表示类型, 这个类型在使用时才确定。

泛型类: 在class的定义后面加入<T>

泛型的约束
new()要求有默认构造函数,可以调用 new T()
class 要求是class,可以 设置为null


public partial class IntVector
{
    public int x;
    public int y;

    public IntVector(int x, int y)
    {
        this.x = x;
        this.y = y;
        public void Print() { ...}
    }
}

public partial class FloatVector
{
    public float x;
    public float y;

    public FloatVector(float x, float y)
    {
        this.x = x;
        this.y = y;
        public void Print() { ...}
    }
}
// class FloatVector 与 class IntVector 出来参数的类型不一样 其他都一样这时候就可以使用泛型抽象他们成

// 泛型的约束:
// new()要求有默认构造函数,可以调用 new T()
// class 要求是class,可以 设置为null

public partial class TVector<T>
{
    public T x;
    public T y;

    public TVector(T x, T y)
    {
        this.x = x;
        this.y = y;
        public void Print() { ...}
    }
}

// 以下是使用

IntVector iv = new IntVector(0, 1);  //语句a 语句b 在功能上相等
TVector<int> Tiv = new TVector(0, 1);  //语句b 语句a 在功能上相等

IntVector fv = new FloatVector(0, 1);  //语句c 语句d 在功能上相等
TVector<float> Tfv = new TVector(0, 1);  //语句d 语句c 在功能上相等

泛型函数:

public static void attack(T a, T b) where T : Actor
{
a.attack();
b.attack();
}

这个方法的作用是让两个 Actor 类型(或其子类)的对象相互攻击。由于使用了泛型,这个方法可以适用于 Actor 的任何子类,提高了代码的复用性和灵活性。

除了 where 关键字,C# 还提供了几种方式来限制泛型参数的类型。以下是一些主要的选项:

  1. 直接在泛型参数中指定基类:
public static void Method<T>(T item) where T : BaseClass
  1. 指定接口:
public static void Method<T>(T item) where T : IInterface
  1. 要求默认构造函数:
public static void Method<T>() where T : new()
  1. 值类型约束:
public static void Method<T>(T item) where T : struct
  1. 引用类型约束:
public static void Method<T>(T item) where T : class
  1. 未装箱的可为 null 的值类型(C# 8.0+):
public static void Method<T>(T item) where T : unmanaged
  1. 非 null 约束(C# 8.0+):
public static void Method<T>(T item) where T : notnull
  1. 多个约束的组合:
public static void Method<T>(T item) where T : BaseClass, IInterface, new()

这些约束可以单独使用,也可以组合使用,以满足特定的需求。每种约束都有其特定的用途,可以帮助你更精确地控制泛型类型参数的特性。

容器

  • Array 数组 固定长度[]Length
  • List 动态数组,自动增长
  • Dictionary 字典 使用Key 来获取Value
  • HashSet 哈希set 唯一[]Contains
  • Queue 队列 可动态增长先进先出 Enqueue Dequeue
  • Stack 栈 可动态增长 后进先出 Push Pop

List 动态数组 自动变长

private static void TestList()
{

    var lst = new List<int>() {3, 4, 5};
    lst.Add(8);
    // 在末尾增加
    lst.Insert(2, 9);
    // 在下标2 中插入 9
    lst.RemoveAt(2);
    // 移除下标2 中的元素
    lst[2] = 15;
    // 修改下标2 中的内容
    lst.Sort();
    // 排序
}


Dictionary 字典 key,value键值对 哈希表

var dict = new Dictionary<int, string>() {
    {3,"_3"},
    {5, "_5" },
};

dict.Add(8, "_8"); 
// 插入 对应的元素PrintCollections(dict, "dict add");
// 如果不存在则插入对应的元素,存在的话则修改 key =2 对应的内容为"_2"dict[2] = "_2";

dict[2] = "_@2";
// 如果存在key =2,则去除对应的值,放到变量val 中,并返回true,否则返回false
ContainsKey
TryGetValue
if (dict.TryGetValue(2, out string val)){
    PrintCollections(dict, "dict TryGetValue succ " + val);
};
    
// 查询是否存在 Key = 33
查询是否存在 Key = 33
PrintCollections(dict, "dict ContainsKey 33 = " + dict.ContainsKey(33));// 尝试移除key =8 元素,如果之前存在,返回true,否则返回false

var isSucc8 = dict.Remove(8);
var isSucc7 = dict.Remove(7);
PrintCollections(dict, "dict Remove7" + isSucc7);

// 获取所有的Key
PrintCollections(dict.Keys, "dict Keys");
// 获取所有的Value
PrintCollections(dict.Values, "dict Values");

HashSet 哈希set 保证里面的元素唯一

var set = new HashSet<int>() {
    3, 4, 5
};

PrintCollections (set,"init HashSet");  // 3 4 5

PrintCollections (set,"HashSet Add 8 = " + set.Add(8)); // true 3 4 5 8

PrintCollections (set,"HashSet Add 8 = " + set.Add(8)); // false 3 4 5 8

PrintCollections (set,"HashSet Remove2 = " + set.Remove(3)); // True 4 5 8

PrintCollections (set,"HashSet Contains 8 =" + set.Contains(8))  // True 4 5 8
// Contains是否包含指定的

Queue 队列 可动态增长 先进先出 Enqueue ()二二二() Dequeue


// 先进先出
var queue = new Queue<int>();
queue1.Enqueue(1);
queue1.Enqueue(2);
queue1.Enqueue(3);
queue1.Enqueue(4);
PrintCollections(queue1, "init Queue");

queue1.Enqueue(8);

PrintCollections(queue1, "Queue Push 8");
PrintCollections(queue1, "Queue Pop" + queue1. Dequeue());

queue1.Enqueue(9);
PrintCollections(queue1,"Queue Push 9");

PrintCollections(queue1,"Queue Pop =" + queue1.Dequeue());
PrintCollections(queue1,"Queue Pop =" + queue1.Dequeue());

PrintCollections(queue1,"Queue count =" + queue1.Count());

stack 后进先出

Push-> ()二二二)

Pop <-
Push Pop


// 先进先出
var stack = new Queue<int>();
stack1.Push(1);
stack1.Push(2);
stack1.Push(3);
stack1.Push(4);
PrintCollections(stack1, "init Queue");

stack1.Push(8);

PrintCollections(stack1, "Queue Push 8");
PrintCollections(stack1, "Queue Pop" + stack1. Pop());

stack1.Push(9);
PrintCollections(stack1,"Queue Push 9");

PrintCollections(stack1,"Queue Pop =" + stack1.Pop());
PrintCollections(stack1,"Queue Pop =" + stack1.Pop());

PrintCollections(stack1,"Queue count =" + stack1.Count());

标签:PrintCollections,C#,void,基础,Queue,queue1,dict,public
From: https://www.cnblogs.com/Leason12138/p/18397034

相关文章

  • C# 高级教程
    JS.InvokeVoidAsync可以异步调用挂载到Window上的方法,而不读取返回的值JS.InvokeAsync可以异步调用挂载到Window上的方法,并读取返回的值通常JS.InvokeAsyncC#高级教程一、C#特性(Attribute)特性简介:特性是一种为程序元素(如类、方法、属性等)附加额外信息的机制。这些额外信......
  • 探秘JavaScript深度领域:精通面向对象编程、虚拟DOM等核心技术
    JaScript作为前端开发的核心技术之一,凭借其强大的灵活性和广泛的应用场景,吸引了大量开发者深入学习。在探秘JaScript的深度领域时,面向对象编程和虚拟DOM等核心技术无疑是两个重要的学习方向。面向对象编程(OOP)在JaScript中扮演着重要角色。虽然JaScript是一种基于原型的语言,而非传......
  • 十六进制转RGB ---颜色-color
    ```//十六进制转RGBfunctionhexToRgb(hex:string){constresult=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);returnresult?[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16),]:null;}functionadjustColor(color:......
  • 探索CSS奥秘:深入解析版式布局与字体样式的应用技巧
    在现代网页设计中,CSS(层叠样式表)扮演着至关重要的角色,它不仅能美化网页,还能通过精细的版式布局和字体样式设计,为用户带来更好的浏览体验。无论是新手设计师还是经验丰富的前端开发者,深入理解和掌握CSS的应用技巧,都是必不可少的技能。本文将带你一起探索CSS在版式布局与字体样式中的......
  • mac 上golang编译 安卓系统的so 错误 'android/log.h' file not found
    lib.gopackagemainimport"C"//exportSpeedTestfuncSpeedTest(config*C.char){ configContent:=C.GoString(config) run(configContent)}funcmain(){}需要安装NDK,用Androidstudio安装,在SDKManeger的SDKTool里选择安装NDK(sidebyside),成功后一般在......
  • 如何使用confluence rest api(wiki自动化),如何解决confluence登录认证问题
    想要使用AtlassianConfluence提供的RESTAPI中的getUser方法来获取用户信息。1.如何使用账号密码登录以下是一个示例Python脚本,演示如何使用该API:importrequestsimportjson#设置ConfluenceAPI的基本URL和登录的用户名密码base_url='https://your-confluence-url/......
  • unity ui控件与C#脚本类对应表
    unityui控件与C#脚本类对应表原文中文C#--classesImage图像ImageText-TextMeshPro文本-TextMeshPrcTMP_TextRawImage原始图像RawImagePanel面板ImageToggle切换ToggleSlider滑动条SliderScrollbar滚动条ScrollbarScrollView滚动......
  • 深入理解JavaScript类与对象:揭秘类字段和静态属性的妙用,js静态属性和实例属性
    在深入理解JaScript类与对象的过程中,类字段和静态属性是两个关键的概念,掌握它们的用法可以让你在实际开发中更加得心应手。虽然JaScript在ES6之前并没有类的概念,但通过ES6及以后的版本,引入了类语法糖,使得我们能够更直观地定义和使用类。类字段是指在类中直接定义的属性,而不是在构......
  • win11+docker desktop导入镜像运行容器
    一:配置环境前置条件:Win11环境,docker注册账号1.安装WSL(1)在windowsstore安装Ubuntu20.04.6(2)设置“控制面板”-“程序”-“程序和功能”-左侧“启用或关闭Windows功能”-打开“适用于Linux的Windows子系统”,“Windows虚拟机监控程序平台”(3)终端执行:sudoaptupdatesudoapt......
  • 升级程序后报错 :Parse error: syntax error, unexpected ':', expecting
    当您看到类似“Parseerror:syntaxerror,unexpected':',expecting...”这样的错误时,这通常是因为PHP代码中存在语法错误。具体来说,这通常是因为某个语法特性在当前PHP版本中不被支持。常见原因PHP版本不兼容:新代码可能使用了较新版本的PHP语法特性,而当前服务器上......