class constructor c# 入門
>class constructor コンストラクタ
コンストラクタとはインスタンスが作成時に実行される処理です。
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 WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
person taro = new person();
taro.print();
}
class person
{
int age;
string name;
public person()
{
age = 20;
}
public void print()
{
Console.Write(age);
}
}
}
}
vb
構文
アクセス修飾子 Sub New ()
処理
End Sub
サンプル
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim taro As New person
taro.print
End Sub
Class person
Dim age As Integer
Dim name As String
Public Sub New()
age = 20
End Sub
Sub print()
Console.Write(age)
End Sub
End Class
End Class
引数のあるコンストラクタ
C#
構文
public person(型 変数名,型 変数名)
{
処理
}
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 WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
person taro = new person(20, “taro”);
taro.print();
}
class person
{
int age;
string name;
public person(int _age,string _name)
{
age = _age;
name = _name;
}
public void print()
{
Console.Write(age + name);
}
}
}
}
実行結果は
20taro
vb
構文
public クラス名(型 変数名,型 変数名)
{
処理
}
サンプル
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim taro As New person(20, “taro”)
taro.print
End Sub
Class person
Dim age As Integer
Dim name As String
Public Sub New(ByVal _age As Integer,ByVal _name As String)
age = _age
name = _name
End Sub
Sub print()
Console.Write(age & name)
End Sub
End Class
End Class
実行結果は
20taro