2

我有一个这样定义的类:

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
    }
}
4

1 回答 1

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();
于 2012-12-11T15:37:18.953 回答