ASP.NET Razor -C#変数
変数は、データを格納するために使用される名前付きエンティティです。
変数
変数はデータを格納するために使用されます。
変数の名前は英字で始まる必要があり、空白や予約文字を含めることはできません。
変数は、格納するデータの種類を示す特定のタイプにすることができます。文字列変数は文字列値( "Welcome to W3Schools")を格納し、整数変数は数値(103)を格納し、日付変数は日付値を格納します。
変数はvarキーワードを使用するか、タイプを使用して宣言されます(宣言する場合はtype)ですが、ASP.NETは通常、データタイプを自動的に判別できます。
例
//
Using the var keyword:
var greeting = "Welcome to W3Schools";
var
counter = 103;
var today = DateTime.Today;
// Using data types:
string greeting = "Welcome to W3Schools";
int counter = 103;
DateTime
today = DateTime.Today;
データ型
以下は、一般的なデータ型のリストです。
Type | Description | Examples |
---|---|---|
int | Integer (whole numbers) | 103, 12, 5168 |
float | Floating-point number | 3.14, 3.4e38 |
decimal | Decimal number (higher precision) | 1037.196543 |
bool | Boolean | true, false |
string | String | "Hello W3Schools", "John" |
演算子
演算子は、式で実行するコマンドの種類をASP.NETに指示します。
C#言語は多くの演算子をサポートしています。以下は、一般的な演算子のリストです。
Operator | Description | Example |
---|---|---|
= | Assigns a value to a variable. | i=6 |
+ - * / |
Adds a value or variable. Subtracts a value or variable. Multiplies a value or variable. Divides a value or variable. |
i=5+5 i=5-5 i=5*5 i=5/5 |
+= -= |
Increments a variable. Decrements a variable. |
i += 1 i -= 1 |
== | Equality. Returns true if values are equal. | if (i==10) |
!= | Inequality. Returns true if values are not equal. | if (i!=10) |
< > <= >= |
Less than. Greater than. Less than or equal. Greater than or equal. |
if (i<10) if (i>10) if (i<=10) if (i>=10) |
+ | Adding strings (concatenation). | "w3" + "schools" |
. | Dot. Separate objects and methods. | DateTime.Hour |
() | Parenthesis. Groups values. | (i+5) |
() | Parenthesis. Passes parameters. | x=Add(i,5) |
[] | Brackets. Accesses values in arrays or collections. | name[3] |
! | Not. Reverses true or false. | if (!ready) |
&& || |
Logical AND. Logical OR. |
if (ready && clear) if (ready || clear) |
データ型の変換
あるデータ型から別のデータ型への変換が役立つ場合があります。
最も一般的な例は、文字列入力を整数や日付などの別の型に変換することです。
原則として、ユーザーが数値を入力した場合でも、ユーザー入力は文字列として送信されます。したがって、数値入力値は、計算に使用する前に数値に変換する必要があります。
以下は、一般的な変換方法のリストです。
Method | Description | Example |
---|---|---|
AsInt() IsInt() |
Converts a string to an integer. | if (myString.IsInt()) {myInt=myString.AsInt();} |
AsFloat() IsFloat() |
Converts a string to a floating-point number. | if (myString.IsFloat()) {myFloat=myString.AsFloat();} |
AsDecimal() IsDecimal() |
Converts a string to a decimal number. | if (myString.IsDecimal()) {myDec=myString.AsDecimal();} |
AsDateTime() IsDateTime() |
Converts a string to an ASP.NET DateTime type. | myString="10/10/2012"; myDate=myString.AsDateTime(); |
AsBool() IsBool() |
Converts a string to a Boolean. | myString="True"; myBool=myString.AsBool(); |
ToString() | Converts any data type to a string. | myInt=1234; myString=myInt.ToString(); |