gpt4 book ai didi

c# - 通过反射获取属性类型

转载 作者:行者123 更新时间:2023-11-30 23:06:42 25 4
gpt4 key购买 nike

我在通过反射获取属性类型时遇到了一点问题。

我有一个类,它只包含简单的类型,如字符串、整数、小数......

public class simple 
{
public string article { get; set; }
public decimal price { get; set; }
}

现在我需要通过反射获取这些属性并按其类型处理它们。

我需要这样的东西:

Type t = obj.GetType();
PropertyInfo propInfo = t.GetProperty("article");
Type propType = ?? *GetPropType*() ??

switch (Type.GetTypeCode(propType))
{
case TypeCode.Decimal:
doSome1;
break;
case TypeCode.String:
doSome2;
break;
}

对于字符串,它可以做到propInfo.PropertyType.UnderlyingSystemType 为 GetPropType() 但不是十进制。

适用于小数 propInfo.PropertyType.GenericTypeArguments.FirstOrDefault(); 但不适用于字符串。

Hos可以获取所有简单类型的类型吗?

最佳答案

您可以使用 PropertyType 来确定是 string 还是 decimal。像这样尝试;

Type t = obj.GetType();
PropertyInfo propInfo = t.GetProperty("article");
if (propInfo.PropertyType == typeof(string))
{
Console.WriteLine("String Type");
}
if (propInfo.PropertyType == typeof(decimal)
|| propInfo.PropertyType == typeof(decimal?))
{
Console.WriteLine("Decimal Type");
}

关于c# - 通过反射获取属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47953420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com