I have automatically generated service references and I need to analyze them to identify classes with public properties that return enums
. This is for an asp.net project that was originally serializing enums as int
and was converted to string
, so I'm trying to produce a list of enums and their int/string values.
I just copied & pasted all of the service references into a .NET console project and I'm able to enumerate the properties and I am focusing on a known enum for testing, but the output from the below code is not identifying it as an enum when it is:
[AxdEntity_PurchTable_1\Property\PurchStatus]: Nullable`1; False
How can I correctly identify it as an enum
?
My Reflection Code:
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?
}
}
}
Automatically generated service reference sample code:
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,
}
}
CodePudding user response:
PurchStatus
property type is not just enum, but nullable enum. Use Nullable.GetUnderlyingType
(returns null
if type is not nullable so coalesce with type itself):
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
}
}
}
CodePudding user response:
You have to check if the generic type is Nullable<>
and if its parameter is an enum. This should detect normal and nullable enum properties:
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);
}
}
}