property get set c# 入門
property プロパティ
クラスのプロパティを解説していきます。
構文
アクセス修飾子 型 プロパティ名
{
get
{
return 値;
}
set
{
}
}
setにはセットをして
getで値を返します。
プロパティを使うためには
※プロパティの値を扱う変数を宣言しとく
必要があります。
プロパティに値を設定するのは
インスタンス.プロパティ名 = 値
サンプル c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
person taro = new person();
taro._age = 20;
taro._name = “taro”;
Console.Write(taro._age + taro._name);
}
class person
{
int age;
string name;
public int _age
{
get
{
return age;
}
set
{
age = value;
}
}
public string _name
{
get
{
return name;
}
set
{
name = value;
}
}
}
}
}
実行結果は
20taro
setで条件文を書いて正確な値が入っているか判定したりする使い方もあります。
その前にエラーチェックをしたほうがいいという考え方もあります。
いちいちgetsetを書くのは大変ですね。
前回はコンストラクタを使いました。
vbのプロパティも解説します。
構文
Public Property _age As 型
Get
Return 値
End Get
Set(ByVal value As 型)
End Set
End Property
サンプル vb
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim taro As New person
taro._age = 20
taro._name = “taro”
Console.Write(taro._age & taro._name)
End Sub
Class person
Dim age As Integer
Dim name As String
Public Property _age As Integer
Get
Return age
End Get
Set(ByVal value As Integer)
age = value
End Set
End Property
Public Property _name As String
Get
Return name
End Get
Set(ByVal value As String)
name = value
End Set
End Property
End Class
End Class
実行結果は
20taro