为什么默认的构造函数不显示此值类型? [英] Why default constructor does not appear for value types?
问题描述
下面的代码片段给了我一个类型的构造函数和方法的列表。
The below snippet gives me a list of constructors and methods of a type.
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();
}
}
但是当我通过一个'诠释'类型的这种方法,为什么不让我看到在输出中隐含的构造?或者说,我怎么修改上面的code列出了默认的构造函数,以及(在情况下,我失去了一些东西在我的code)。
But when I pass an ‘int’ type to this method, why don’t I see the implicit constructor in the output? Or, how do I modify the above code to list the default constructor as well (in case I’m missing something in my code).
推荐答案
在C#(和大多数CLI语言) - 指定在一个结构参数的构造函数是被禁止的,因此,一个结构在C#(和大多数其他创建的。 NET语言)甚至不会在IL中定义的参数的构造函数。在CLR始终使用定义的规则(基本上,填充零当量所有值)初始化值类型,和C#强制执行,作为唯一的选择。
In C# (and most CLI languages) - specifying a parameterless constructor on a struct is forbidden, and as such, a struct created in C# (and most other .NET languages) will not even have a parameterless constructor defined in the IL. The CLR always initializes value types using defined rules (basically, filling all values with zero equivalents), and C# enforces that as the only option.
由于默认,参数的构造函数中不产生结构C#的存在,它不使用反射时显示。
Since the default, parameterless constructor does not exist in a C# generated struct, it does not display when using reflection.
这篇关于为什么默认的构造函数不显示此值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!