グローバル データは、ドキュメント レベルでメモリに一時的に保存することができます。
AutoCAD プログラムは、マネージ アプリケーションをロードするとき、アプリケーションのアセンブリで 1 つまたは複数の PerDocumentClass カスタム属性をクエリーします。この属性のインスタンスが見つかると、各属性と関連付けられているタイプのインスタンスが、AutoCAD 作図環境で開いているドキュメントそれぞれに対して作成されます。さらに、このタイプの新しいインスタンスは、これ以降に開かれたドキュメントに対しても作成されます。
PerDocumentClass 属性と関連付けられているタイプは、ドキュメント引数を取る Public コンストラクタ、またはドキュメント引数を取り、このタイプのインスタンスを返す Public Static Create メソッドのいずれかを備えている必要があります。Create メソッドが存在する場合はこのメソッドが使用され、そうでない場合はコンストラクタが使用されます。タイプ インスタンスの作成対象であるドキュメントがドキュメント引数として渡されるので、タイプ インスタンスは関連付けられているドキュメントを知ることができます。
次の手順で、PerDocumentClass 属性の使用方法を説明します。
...
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
[assembly: PerDocumentClass(typeof(CSPerDoc.PerDocData))]
namespace CSPerDoc
{
// Defines a global class for constant values
public static class CSPerDocConsts
{
public const string dbLocVarName = "dbLoc";
}
// Defines the main class
public class PerDocCommands
{
// Creates a command that returns the current value of the per document data
[CommandMethod("DatabaseLocation")]
public void DatabaseLocation()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
PerDocData pDData = (PerDocData) acDoc.UserData[CSPerDocConsts.dbLocVarName];
if (pDData == null) {
acDoc.Editor.WriteMessage("\nNo user data assigned.");
} else {
acDoc.Editor.WriteMessage("\n" + pDData.DbLocation);
}
}
}
// Defines the class that wuill be used to initialize the per document data
public class PerDocData
{
// Define the internal/member variables of the class
private string _stDbLoc;
// Expose a public property that returns the value of the internal variable
public string DbLocation
{
get { return _stDbLoc; }
}
// Public constructor that requires a Document object
// Created by AutoCAD when the application is loaded
public PerDocData(Document acDoc)
{
_stDbLoc = @"";
acDoc.UserData.Add(CSPerDocConsts.dbLocVarName, this);
}
// Create method: Required constructor for the class
public static PerDocData Create(Document acDoc)
{
PerDocData pDData = new PerDocData(acDoc);
pDData._stDbLoc = @"C:\\ABCApp\\ProjectData\\" + acDoc.Name.Remove(acDoc.Name.Length - 4) + ".db";
return pDData;
}
}
}