LoginSignup
4
9

More than 3 years have passed since last update.

同じソリューション内の別プロジェクトを参照する方法

Last updated at Posted at 2021-03-19

概要

以下のように1つのソリューション内にCommon, Food, Sportsと複数のプロジェクトがある。
Commonにあるクラスや関数をFoodやSportsから使いたいというときのやり方を紹介する。
image.png

  • 目的
    • VisualStudioの使い方を知る
  • 本記事のゴール
    • 同ソリューション内の別プロジェクトを参照できるようになる
  • 対象者
    • VisualStudio初心者
  • 環境・バージョン
    • VisualStudio2017

手順

1.参照の追加

SportsプロジェクトからCommonにあるクラスや関数を使いたい場合、
Sportsプロジェクトの[参照]を右クリックして[参照の追加]をクリックする。

image.png

参照マネージャーの左のメニューから[プロジェクト]-[ソリューション]を選択し、Commonにチェックを入れ[OK]ボタンを押す。

image.png

[参照]の中にCommonが追加される。

image.png

2.ソースの書き方

例えばCommonプロジェクトに自己紹介文を作成するCreateIntroductionという関数があり、それをSportsプロジェクトから使いたい場合。

Common Class1.cs
namespace Common
{
    public class Class1
    {
        /// <summary>
        /// 自己紹介文を作成します。
        /// </summary>
        /// <param name="strFavorite">好きなもの</param>
        /// <returns>自己紹介文</returns>
        public static string CreateIntroduction(string strFavorite)
        {
            string strIntroduction = "私の好きなものは{0}です。";
            return string.Format(strIntroduction, strFavorite);
        }
    }
}

Sportsプロジェクトは、フォーム[Form1]の上にラベル[label1]を置いている状態。
image.png

Sportプロジェクトでは、Common.Class1.CreateIntroduction("野球")こんな感じで使用できる。
※CreateIntroduction関数がstaticなのでこう書ける。staticでない場合はまた別。(後ほど別記事で説明予定)

Sports Form1.cs
namespace Sports
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // Commonプロジェクトの関数を使えるようになった
            this.label1.Text = Common.Class1.CreateIntroduction("野球");
        }
    }
}

Usingディレクティブを使ってもよい。

Sports Form1.cs
// Usingディレクティブを使った場合
using Common;

namespace Sports
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // 「Common.」は書かなくてもCommonの中のClass1なんだと分かってくれる
            this.label1.Text = Class1.CreateIntroduction("野球");
        }
    }
}

動かすとこんなふうに表示される。
image.png

4
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
9