以下のスニペットは、タイプのコンストラクタとメソッドのリストを私に提供します。デフォルトのコンストラクタが値型に対して表示されないのはなぜですか?
static void ReflectOnType(Type type)
{
Console.WriteLine(type.FullName);
Console.WriteLine("------------");
List<ConstructorInfo> constructors =
type.GetConstructors(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |BindingFlags.Instance | BindingFlags.Default).ToList();
List<MethodInfo> methods = type.GetMethods().ToList();
Type baseType = type.BaseType;
while (baseType != null)
{
constructors.AddRange(baseType.GetConstructors(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Default));
methods.AddRange(baseType.GetMethods());
baseType = baseType.BaseType;
}
Console.WriteLine("Reflection on {0} type", type.Name);
for (int i = 0; i < constructors.Count; i++)
{
Console.Write("Constructor: {0}.{1}", constructors[i].DeclaringType.Name, constructors[i].Name);
Console.Write("(");
ParameterInfo[] parameterInfos = constructors[i].GetParameters();
if (parameterInfos.Length > 0)
{
for (int j = 0; j < parameterInfos.Length; j++)
{
if (j > 0)
{
Console.Write(", ");
}
Console.Write("{0} {1}", parameterInfos[j].ParameterType, parameterInfos[j].Name);
}
}
Console.Write(")");
if (constructors[i].IsSpecialName)
{
Console.Write(" has 'SpecialName' attribute");
}
Console.WriteLine();
}
Console.WriteLine();
for (int i = 0; i < methods.Count; i++)
{
Console.Write("Method: {0}.{1}", methods[i].DeclaringType.Name, methods[i].Name);
// Determine whether or not each field is a special name.
if (methods[i].IsSpecialName)
{
Console.Write(" has 'SpecialName' attribute");
}
Console.WriteLine();
}
}
しかし、このメソッドに 'int'型を渡すと、暗黙のコンストラクタが出力に表示されないのはなぜですか?または、上記のコードを変更して、デフォルトのコンストラクタも一覧表示するにはどうすればよいですか(コード内に何かがない場合に備えて)。
興味深い読み取りがことがありますhttp://msmvps.com/blogs/jon_skeet/archive/2008/12/10/value-types- and-parameterless-constructors.aspx –