[Conditional("DEBUG"), Conditional("TEST1")] void TraceMethod() { (略) }
namespace AttrTst { //クラスと構造体にしか付けられない属性であることを明記 [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] public class AuthorAttribute : Attribute { public AuthorAttribute(string name) { this.name = name; version = 1.0; } public double version; string name; } [Author("カーネル",version=1.1)] public class cTst { static void Main() { } } }
属性の情報はリフレクションを使って取得する。
using System; using c = System.Console; // alias namespace AttrTst { //クラスと構造体にしか付けられない属性であることを明記 [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] public class AuthorAttribute : Attribute { public AuthorAttribute(string name) { this.name = name; version = 1.0; } double version; public double Version { set{version = value;} get{return version;} } string name; public string Name { get{return name;} } } [Author("カーネル",Version=1.1)] public class cTst { static void Main() { PrintAuthorInfo(typeof(cTst)); c.ReadLine(); } public static void PrintAuthorInfo(Type t) { Console.WriteLine("Author information for {0}", t); Attribute[] attrs = Attribute.GetCustomAttributes(t); foreach(Attribute attr in attrs) { if (attr is AuthorAttribute) { AuthorAttribute a = (AuthorAttribute)attr; c.WriteLine(" {0}, version {1:f}",a.Name, a.Version); } else { c.WriteLine(attr.ToString()); } } } } }
実行結果
Author information for AttrTst.cTst カーネル, version 1.10
GetCustomAttributesがコールされたタイミングでAuthorAttributeクラスが生成される。
条件付でコンパイルするメソッドを定義できる。デバッグ時だけ呼ばれるメソッドとか。くわしくはヘルプ参照
定義のところで以下のように書いておくと
[Obsolete("古いモジュールのために残してあるだけなのでできるだけ使わないように。")] public int a;
コンパイル時にワーニングが出るようになる。
warning CS0618: 'AttrTst.cTst.a' は古い形式です : '古いモジュールのために残してあるだけなのでできるだけ使わないように。'
マネージ メモリ内のクラスまたは構造体のデータ フィールドの物理的なレイアウトを制御。
Cで言うところの #pragma pack の代わりに使えそう。ただしクラスとか構造体単位。
/* C言語だとこのようになる構造体を渡したい場合 #define ALLOC_COUNT 128 typedef struct tagTIME_INFO_EX{ int YYYY; int MM; int DD; int hh; int mm; int ss; char str[ALLOC_COUNT]; } TIME_INFO_EX, *PTIME_INFO_EX; */ // C#ではこう書く [StructLayout( LayoutKind.Sequential, Pack = 4 )] public struct TIME_INFO_EX { public int YYYY; public int MM; public int DD; public int hh; public int mm; public int ss; [MarshalAs( UnmanagedType.ByValArray, SizeConst = 128 )] public char[] str; // C++: char str[128]; } //呼び出す側 [DllImport( "myutil.dll", EntryPoint = "GetNowTimeStructEx" ) ] public static extern int GetNowTimeStructEx( out TIME_INFO_EX timeinfoEx ); TIME_INFO_EX timeinfoEx; GetNowTimeStructEx( out timeinfoEx );
[DefaultEvent("Hoge")] public class MyControl : ..... { public event EventHandler Hoge; }