c# - 为什么值类型不出现默认构造函数?

标签 c# .net

下面的代码片段为我提供了一个类型的构造函数和方法列表。

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”类型传递给此方法时,为什么我在输出中看不到隐式构造函数?或者,我如何修改上述代码以同时列出默认构造函数(以防我的代码中遗漏某些内容)。

最佳答案

在 C#(和大多数 CLI 语言)中 - 禁止在结构上指定无参数构造函数,因此,在 C#(和大多数其他 .NET 语言)中创建的结构甚至不会在 IL 中定义无参数构造函数. CLR 总是使用定义的规则初始化值类型(基本上,用零等价物填充所有值),而 C# 强制将其作为唯一选项。

由于 C# 生成的结构中不存在默认的无参数构造函数,因此在使用反射时不会显示。

关于c# - 为什么值类型不出现默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4687289/

相关文章:

c# - 在 C# 中,如何在不四舍五入的情况下获得所需的小数点数?

c# - 我如何区分 C# 中的两个相同对象?

.net - New之后什么都没有,有可能吗?

.net - 让 .NET 考虑完全信任特定的网络共享

c# - onChange 事件未触发 Blazor InputSelect

c# - 将 C++/CLI 桥接到 C# 时防止垃圾回收

c# - 如何在忽略定界符的情况下拆分字符串?

.net - 使用大文件作为消息负载进行发布/订阅

c# - Automapper 正在丢失引用

c# - 有人可以解释幕后发生的事情吗?