c# - 为什么 int 属性的 IsValueType 为 false?

标签 c# .net-core

再见,

我对这个问题很沮丧,我创建了一个简单的类,如下所示:

public class Classe
{
    public int Intero { get; set; }

    public Int32 Intero32 { get; set; }

    public double Double { get; set; }

    public string Stringa { get; set; }

    public Classe PerReferenza { get; set; }
}

我编写这个扩展方法的目的是返回属性的默认值(引用类型或值类型):

public static class TypeExtensions
{
    public static object GetDefaultValue(this Type t)
    {
        if (t.IsValueType)
            return Activator.CreateInstance(t);

        return null;
    }
}

按照我的主要方法:

static void Main(string[] args)
{
    Classe c = new Classe();

    foreach (var proprietà in c.GetType().GetProperties())
    {
        var predefinito = proprietà.GetType().GetDefaultValue();

        Console.WriteLine($"Default for {proprietà}: {predefinito ?? "NULL"}");
    }

    Console.ReadKey();
}

这是我的输出:

Default for Int32 Intero: NULL
Default for Int32 Intero32: NULL
Default for Double Double: NULL
Default for System.String Stringa: NULL
Default for ConsoleApp1.Classe PerReferenza: NULL

我不明白为什么我总是得到所有属性的 FALSE... 预期的输出是:

Default for Int32 Intero: 0
Default for Int32 Intero32: 0
Default for Double Double: 0
Default for System.String Stringa: ""
Default for ConsoleApp1.Classe PerReferenza: null

非常感谢...

最佳答案

你的意思是proprietà.PropertyType.GetDefaultValue();您目前正在询问 RuntimePropertyInfo 是否是值类型(它不是)。

关于c# - 为什么 int 属性的 IsValueType 为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54519527/

相关文章:

c# - Xamarin Android,打开许多应用程序时崩溃

java - 在 for 循环中获取枚举的序数 [c#]

asp.net-core-mvc - AddEntityFrameworkStores 只能使用派生自 .NET Core 2.0 中的 IdentityRole 的角色调用

asp.net-core - .net core 在运行时加载 *.deps.json 以加载依赖程序集的正确版本

c# - 如何延迟停止和启动函数应用

具有代理凭据的 C# HttpWebRequest 未将凭据传递给代理服务器

c# - 设计器显示 : Invalid Xaml

C# 将 Active Directory 十六进制转换为 GUID

.net-core - 使用 DotNetRDf.Query.FullText 创建 Lucene 索引器时出现异常

c# - 如何在没有不安全关键字的情况下获取结构的 Span<byte> View