This article mainly introduces the parameters and special types and characteristics in ASP.NET. It is very good and has reference value. Friends in need can refer to it
1. Optional parameters and named parameters
## 1. Optional parameters
## eg:
static void BookList(string category,int pageIndex = 1) { //操作 } //调用 static void Main(string[] args) { BookList("C#"); //使用全部默认参数 BookList("C#",2) //不使用默认参数 }
Syntax:
Method name (parameter 1 name: parameter 1 Value...Parameter n name: Parameter n value) Special types
1 name: Attribute 1 value,...Attribute n name: Attribute n value} The assignment of attributes in anonymous types is one-time, that is, the attributes of anonymous pairs are read-only.
#4, Dynamic and VAR keywords. ?
var can only be used for local variables, not fields and parameters; it must be initialized at the time of declaration; the type of the variable is determined at compile time Fields, method parameters, method return values, can be used for generic type parameters, etc.; can be assigned or assigned to any type Can be assigned or assigned to any type
5. Nullable type 1. Syntax:
类型?变量名
eg:
System.Nullable<int> num = null; System.Nullable<DateTime> birthday = null; //或 int? num = null; DateTime? birthday = null;
注:当把一个可空类型赋值给一个非空类型时,将引发编译错误
eg:int? num = null; int num2 = num;
2.可以使用可空类型的属性,解决不能把一个可空类型赋值给一个非空类型
(1) HasValue:属于bool类型,当变量包含非空值时,它被设置为true
(2) Value:如果HasValue为true 则说明Value包含有意义的值,否则将引发InvalidOperaionException
int? num1 = 5 int num2 = num1??0;
三、特性
1.C#的特性主要有以下特点
为目标元素(可以是程序集、类、属性、方法)加入附加信息,类似于注释
特性本质上也是一个雷,直接或间接的继承自Acttribute类
特性命名都以Attribute结尾,但是在使用它时可以省略,.NET会自动找到对应得特性类
2.语法
[特性名] 或[特性名(参数值...)]
eg:
[Obsolete] //这个方法可用使用 但是编译时会警告 [Obsolete("不要使用旧的方法,使用新的方法",false)] //这个方法可用使用 但是编译时会警告 [Obsolete("不要使用旧的方法,使用新的方法",true)] //这个方法不可以使用,编译时会报错 static void Old(){ Console.WriteLine("这是旧方法!"); } static void New(){ Console.WriteLine("这是新方法!"); } public static void Main(){ Old(); }
3.自定义特性(继承Attribute)
eg:
[AttributeUsage(AttributeUsages.Class|AttributeUsages.Method,AllowMultiple=true)] [AttributeUsage(AttributeUsages.Class)] //只能在类中进行使用 [AttributeUsage(AttributeUsages.Method)] //只能在方法中进行使用 [AttributeUsage(AllowMultiple=true)] //可以在同一个类上进行多次使用 class DescriptionAttribute:Attribute{ public string name{get;set;} public DescriptionAttribute(){} public DescriptionAttribute(string name){ this.name = name } }
The above is the detailed content of Detailed explanation of parameters and special types of instances in ASP.NET. For more information, please follow other related articles on the PHP Chinese website!