如何知道类的属性类型是否是自定义的

时间:2012-12-11 15:34:20

标签: c# reflection

我有一个像这样定义的类:

public class Company
{
  public Int32 OrganisationID {get;set;}
  public CompanyStatus OrganisationStatus {get;set;} 
  // note that CompanyStatus is my custom type
}

然后我将代码编译成Entity.dll。当我使用以下代码时,我将((System.Reflection.MemberInfo)(properties[1])).Name作为CompanyStatus。如何判断它是否是自定义类型,因为我正在动态读取所有属性?

Assembly objAssembly = Assembly.LoadFrom(@"Entities.dll");

var types1 = objAssembly.GetTypes();

foreach (Type type in types1)
{
    string name = type.Name;
    var properties = type.GetProperties(); // public properties
    foreach (PropertyInfo objprop in properties)
    {
        // Code here
    }
}

1 个答案:

答案 0 :(得分:4)

使用IsPrimitive属性判断属性的类型不是基本类型还是字符串

if(objprop.PropertyType.IsPrimitive || objprop.PropertyType == typreof(string))

来自MSDN

  

基本类型包括Boolean,Byte,SByte,Int16,UInt16,Int32,UInt32,Int64,UInt64,IntPtr,UIntPtr,Char,Double和Single。

您可能还需要检查原始类型的数组等。要查看该类型是否包含其他类型,请使用:

if(objprop.PropertyType.HasElementType)
    var t2 = objprop.PropertyType.GetElementType();
相关问题