c#-constant, field, property and indexer

constant

Constants are class members that represent constant values ​​(values ​​that can be calculated at compile time).
Constants belong to types (classes and structures) rather than to objects, so there is no such thing as "instance constant". Read-only instance fields can be used to act as "instance constants".
It should be noted that read-only fields are variables rather than constants.

// 声明:
[访问修饰符] const 类型 <常量名> = 常量值;

// 例如:
public const int A = 100;
private const string S_ID = "SSS-SSA";

Field

A field is a variable that represents an object or type (classes and structures).

// 字段的声明:
[字段访问修饰符] 类型 <字段名> [ = 初始值];
字段访问修饰符(一个或多个组合):
	new
	public
	protected
	internal
	private
	static
	readonly
	volatile

// 例如:
struct Man
{
    
    
	private int age;
	public static readonly string name = "JJ";
}
class Book
{
    
    
	int id;
	string name;
}

instance fields

class Man
{
    
    
	// 实例字段
	public string name;
}

...

// 使用
Demo1 demo1 = new Demo1();
demo1.a = "YY";

static fields

class Man
{
    
    
	public static string name;
}

...

// 使用
Demo2.a = "UU";

Field initialization timing , instance fields are initialized when the instance is created; static fields are initialized when the class or structure is loaded. Static fields are initialized only once; instance fields are initialized each time the instance is created.

Attributes

Attribute syntax is a natural extension of fields. The field defines the storage location of the data; the attribute contains get and set accessors, which can be used to retrieve the value of the attribute or assign a value to it.

// 属性的声明:
// 1.简略的声明:
	[属性访问修饰符] 类型 <属性名> {
    
    属性访问器声明}
// 2.完整的声明:
	[字段访问修饰符] 类型 <字段名> [= 初始化值];
	[属性访问修饰符] 类型 <属性名> {
    
    属性访问器声明}
属性访问修饰符最常用:
	public
	public static
字段访问修饰符:
	因为要保护起来所以一般是privateprivate static
属性访问器声明:
	getset 之一或全部

// 例如:
class Student
{
    
    
	// 简略声明
	public int age {
    
     get; set; }
	// 完整声明
	private static string name;
    public static string Name
    {
    
    
        get {
    
     return name; }
        set {
    
     name = value; }
    }
}

class Man
{
    
    
	// 字段
	private int age;
	// 属性
	public int Age
	{
    
    
		get
		{
    
    
			return this.age;
		}
		set
		{
    
    
			if (value >= 0 && value <= 150)
				this.age = value;
			else
				throw new Exception("年龄错误!人类年龄应该介于0到150岁之间");
		}
	}
}

Quickly generate attributes in Visaul Studio

  1. Brief statement:
    • Enter prop in the appropriate position and press the Tab key twice.
  2. Full statement:
    • Enter propfull at the verified location and press the Tab key twice.

Regardless of whether it is a brief declaration or a complete declaration, the cursor will be positioned on the data type after generating the attribute declaration . The default type is int . If you need to change it, just enter a new type directly.
After the type is modified (or you plan to use the default data type), press the Tab key once and the cursor will jump to the attribute name part. You can directly modify the attribute name.

explain

Generally speaking, attributes are the protection of fields, such as: man.age = 1000 (someone's age is 1000 years old). Under normal circumstances, a person cannot live to be 1000 years old, but when using fields, you can assign values ​​like this , albeit wrong.
Other programming languages ​​like Java and C++ use get and set methods to protect fields:

// Java代码
public class Man {
    
    
	// 年龄字段
	private int age;
	
	// get方法
	public int getAge() {
    
    
		return this.age;
	}
	// set方法
	public void setAge(int age) {
    
    
		if (age >= 0 && age <= 150) 
			this.age = age;
		else 
			throw new Exception("年龄错误!人类年龄应该介于0到150岁之间");
	}
}
class Man
{
    
    
	// 存储数据的字段
	private string name;
	// 保护字段的属性
    public string Name
    {
    
    
        get {
    
     return name; }
        set {
    
     name = value; }
    }
}
Man man = new Man();

// value是一个上下文关键字,在set访问器这个
// 作用域内表示外部传进来的值,如:
man.Name = "KK";
// 此时value就是"KK".

Attributes are actually a kind of syntax sugar . The internal implementation actually generates two methods (get_attribute name() and set_attribute name(attribute type)). When we use the property's get accessor it will call the get_property name() method, and when we use the property's set accessor it will call the set_property name() method.

Indexer

Indexers enable objects to be indexed in the same way as arrays. As the name suggests, indexers are used to retrieve collections.
Indexers are generally used in collection classes.

class IndexerDemo
{
    
    
	private Dictionary<string, int> dic = new Dictionary<string, int>();
	
	public int? this[string name]
	{
    
    
		get 
		{
    
    
			if (this.dic.ContainsKey(name))
				return this.dic[name];
			else
				return null;
		}
		set 
		{
    
    
			if (this.dic.ContainsKey(name))
				this.dic[name] = value.Value;
			else
				this.dic.Add(name, value.Value);
		}
	}
}

class Demo
{
    
    
	static void Main(string[] args)
	{
    
    
		IndexerDemo i = new IndexerDemo();
		i["JJ"] = 20; // 赋值
		var man = i["JJ"]; // 通过下标的方式索引到数据
	}
}

おすすめ

転載: blog.csdn.net/weixin_45345384/article/details/128110799