繁体   English   中英

如何识别具有枚举返回类型的公共类属性?

[英]How do I identify class properties that are public with an enum return type?

我已自动生成服务引用,我需要分析它们以识别具有返回enums的公共属性的类。 这是一个最初将枚举序列化为int并转换为string的 asp.net 项目,因此我试图生成一个枚举列表及其 int/string 值。

我刚刚将所有服务引用复制并粘贴到一个 .NET 控制台项目中,我能够枚举属性,我专注于一个已知的枚举进行测试,但下面代码的输出没有将其识别为枚举几时:

[AxdEntity_PurchTable_1\Property\PurchStatus]: Nullable`1; False

我怎样才能正确地将它识别为enum

我的反射代码:

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
            where t.IsClass && t.Namespace == "MyNamespace"
            && t.Name == "AxdEntity_PurchTable_1" // I plan to remove this, but focusing on one class
            select t;

foreach (var refClass in q.ToList())
{
    foreach (var prop in refClass.GetProperties())
    {
        if (prop.Name == "PurchStatus")
        {
            // How do I determine if the return type is an enum?
            Console.WriteLine($"[{refClass.Name}\\Property\\{prop.Name}]: {prop.PropertyType.Name}; {prop.PropertyType.BaseType.IsEnum}");

            // OUTPUT: [AxdEntity_PurchTable_1\Property\PurchStatus]: Nullable`1; False

            // prop.PropertyType.BaseType.IsEnum == false?
        }
    }
}

自动生成服务参考示例代码:

namespace MyNamespace
{
    // <... Many other generated classes in this namespace>
    public partial class AxdEntity_PurchTable_1
    {
        private System.Nullable<AxdEnum_PurchStatus> purchStatusField;
        
        // <... Many other properties in this class ...>
        public System.Nullable<AxdEnum_PurchStatus> PurchStatus
        {
            get
            {
                return this.purchStatusField;
            }
            set
            {
                this.purchStatusField = value;
            }
        }
    }
    
    // <... Many other enums in this namespace ...>
    public enum AxdEnum_PurchStatus
    {
        None,
        Backorder,
        Received,
        Invoiced,
        Canceled,
    }
}

您必须检查泛型类型是否为Nullable<>以及它的参数是否为枚举。 这应该检测正常和可为 null 的枚举属性:

foreach (var refClass in q.ToList())
{
    foreach (var prop in refClass.GetProperties())
    {
        if(
            prop.PropertyType.IsEnum
            || (prop.PropertyType.IsGenericType
            && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)
            && prop.PropertyType.GetGenericArguments()[0].IsEnum))
        {
            Console.Write(prop);
        }
    }
}

PurchStatus属性类型不仅是枚举,而且是可为的枚举。 使用Nullable.GetUnderlyingType (如果类型不可为空则返回null ,因此与类型本身合并):

foreach (var refClass in q.ToList())
{
    foreach (var prop in refClass.GetProperties())
    {
        var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
        if (type.IsEnum)
        {
            // do something
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM