統合開発環境 IDE(Integrated Development Environment)
Microsoft Visual C# 2008 Express Edition
今日書いたソースコード。
プロパティを含んだインターフェイス。
using System;
// プロパティのインターフェイス
interface IZahyo
{
// プロパティ
int zx
{
get;
set;
}
int zy
{
get;
set;
}
}
// プロパティのみのインターフェイスを実装
class TaisyoZahyo : IZahyo
{
// フィールド
int x;
int y;
// コンストラクタ
public TaisyoZahyo(int x, int y)
{
this.x = x;
this.y = y;
}
// インターフェイスの実装
public int zx
{
get { return -x; }
set { x = value; }
}
public int zy
{
get { return -y; }
set { y = value; }
}
}
class MainClass
{
// パラメータがIZahyoインターフェイスの靜的メソッド
public static void DisplayZahyo(IZahyo zahyo)
{
Console.WriteLine("x={0},y={1}", zahyo.zx, zahyo.zy);
}
static void Main()
{
TaisyoZahyo z1 = new TaisyoZahyo(5, 10);
// プロパティの参照
Console.WriteLine(z1.zx); // 出力値:-5
Console.WriteLine(z1.zy); // 出力値:-10
TaisyoZahyo z2 = new TaisyoZahyo(-5, -10);
// プロパティの参照
DisplayZahyo(z2); // 出力値:x=5, y=10
}
}
インターフェイスを多重継承。
using System;
// 基本インターフェイス
interface Interface
{
void method(int n);
}
// 基本インターフェイス1
interface Interface1
{
void method1(string a);
}
// 派生インターフェイス
interface ISampleInterface : Interface, Interface1
{
void method2();
}
// 派生インターフェイスの実装
class Sample : ISampleInterface
{
public void method(int n)
{
Console.WriteLine(n);
}
public void method1(string a)
{
Console.WriteLine(a);
}
public void method2()
{
Console.WriteLine("method2");
}
}
class MainClass
{
static void Main()
{
Sample s = new Sample();
s.method(10); // 出力値:10
s.method1("Kamimura"); // 出力値:Kamimura
s.method2(); // 出力値:method2
}
}
インターフェイスを多重実装。
using System;
// インターフェイス
interface Interface
{
void method(int n);
}
// インターフェイス1
interface Interface1
{
void method1(string s);
}
// インターフェイスの多重実装
class Sample : Interface, Interface1
{
public void method(int n)
{
Console.WriteLine(n);
}
public void method1(string s)
{
Console.WriteLine(s);
}
}
class MainClass
{
static void Main()
{
Sample s = new Sample();
s.method(10); // 出力値:10
s.method1("Kamimura"); // 出力値:Kamimura
}
}
今日はインターフェイスについていろいろと学びました。
プログラミング学習が毎日わくわく楽しみな今日この頃です。
0 コメント:
コメントを投稿