Asp.net mvc 如何查找属性的类型,特别是在简单类型和集合类型之间?
我使用的是MVC3、C#、Razor、.NET4、EF5、SQL Server 2008 我需要找出域对象上的属性类型,特别是它是ICollection ie导航属性还是简单的POCO类型ie int、string等 基本上,我是从一个视图映射到一个域对象,我需要排除导航属性(ICollection)。我使用的是值注入器,我可以编写一个自定义注入器来忽略ICollection 我相信有一个“TypeOf”函数 因此,我的伪逻辑大致如下:Asp.net mvc 如何查找属性的类型,特别是在简单类型和集合类型之间?,asp.net-mvc,asp.net-mvc-3,entity-framework,entity-framework-4,entity-framework-5,Asp.net Mvc,Asp.net Mvc 3,Entity Framework,Entity Framework 4,Entity Framework 5,我使用的是MVC3、C#、Razor、.NET4、EF5、SQL Server 2008 我需要找出域对象上的属性类型,特别是它是ICollection ie导航属性还是简单的POCO类型ie int、string等 基本上,我是从一个视图映射到一个域对象,我需要排除导航属性(ICollection)。我使用的是值注入器,我可以编写一个自定义注入器来忽略ICollection 我相信有一个“TypeOf”函数 因此,我的伪逻辑大致如下: Match if not(typeOf(ICollecti
Match if not(typeOf(ICollection))
非常感谢
编辑:
尝试了第一个解决方案,但无法使其工作。下面是示例代码。所有结果都是真的。我希望ISCollection 1和2为假,3和4为真
想法
bool isCollection2 = stdorg.Id is System.Collections.IEnumerable;
bool isCollection3 = stdorg.StdLibraryItems is System.Collections.IEnumerable;
编辑2:
这对我很有用:
bool IsCollection = (stdorg.StdLibraryItems.GetType().Name == "EntityCollection`1")
值注入器实际需要我使用:
bool IsCollection = (stdorg.StdLibraryItems.GetType().Name == "ICollection`1")
这是一种享受。对于那些感兴趣的值,Injector有一个匹配例程,将此条件置于中可确定匹配是否返回true,如果返回true,则将目标属性值设置为源属性值的值。如果您可以使用点语法访问属性或对象,则可以使用is运算符
var obj = new List<string>();
bool collection = obj is System.Collections.IEnumerable; // true since IEnumerable is the base interface for collections in .NET
var obj=新列表();
bool collection=obj是System.Collections.IEnumerable;//由于IEnumerable是.NET中集合的基本接口,因此为true
如果您使用Type.GetMembers
等方法通过反射访问属性,则可以使用t.GetInterface(“System.Collections.IEnumerable”)
。
其中t是该实例的类型。如果该类型未实现所述接口,则方法
GetInterface(string)
将返回null。他是一种通用类型解决方案,也可以解决其他属性问题。
特别是当某个东西可以为空时
foreach (var propertyInfo in typeof (T).GetProperties()) { //<< You know about typeof T already
var propType = UnderLyingType(propInfo);
//if( decide if collection?){}
}
public Type UnderLyingType(PropertyInfo propertyInfo) {
return Nullable.GetUnderlyingType(propertyInfo.PropertyType)
?? propertyInfo.PropertyType;
}
foreach(var propertyInfo in typeof(T).GetProperties()){//请参见上面的编辑。我无法让它工作。所有结果都返回true。谢谢。我最终选择了EDIT2,尽管我已经给出了这个答案,因为它更通用。谢谢