リフレクションで値型(struct)のデフォルトコンストラクタが取得できない
ハマッたのでメモ。結論から書くと、Activator.CreateInstance() を使用すればよい。
サンプルとして下記のクラスと構造体を用意する。
class SampleClass {} struct SampleStruct {}
コイツらのインスタンスをリフレクションで生成したい。つまり、typeof( SampleClass ) とか typeof( SampleStruct ) から、そのインスタンスを生成したいわけ。
僕は、これらのコンストラクタを取得すればいいだろうと考えた。実際、SampleClass については下記のコードでOK。
ConstructorInfo ctor = typeof( SampleClass ).GetConstructor( Type.EmptyTypes ); object instance = ctor.Invoke( null );
ところがだ、SampleStruct で同じようにやっても、うまく行かないのだ。
ConstructorInfo ctor = typeof( SampleStruct ).GetConstructor( Type.EmptyTypes );
とやっても、ctor には null が返ってしまう。
こりゃ困った、Google先生に聞いてみよう、と検索すると次のページがヒットした。
http://www.eggheadcafe.com/software/aspnet/30724219/fastest-way-to-construct.aspxfastest way to construct a struct from a type? - not_a_commie
14-Sep-07 01:56:07
It seems that the only way to construct a struct from a type is to use
Activator.CreateInstance. Is that true? Can anyone improve
(performance-wise) upon this function below:
...
このページ、その先は読んでないので内容は知らないけれど、とにかく Activator.CreateInstance を利用すれば値型も生成できるらしいと分かった。さすがはGoogle先生!
object instance = Activator.CreateInstance( typeof( SampleStruct ) );
バンザイ、ちゃんとインスタンスが生成されました。めでたしめでたし。