Skip to main content
 首页 » 编程设计

c#之如何从对包含类型的引用中获取 ICollection> 属性的名称

2024年02月23日13落叶无声

我有类型引用 A和 B但我想要 ICollection<A> 的名称这是 B 的属性.如果我只有这两种类型,如何获取集合名称“BunchOfX”?

public class X 
{ 
} 
 
public class Y 
{ 
   public virtual ICollection<X> BunchOfX { get; set; } 
} 

当我只有类型引用 A 和 B 时,我需要一些可以给我属性名称“BunchOfX”的东西。假设 A 将引用 ICollection<> 持有的类型,B 将引用 ICollection 的类型<> 定义于.

真正的代码

var entityType = Type.GetType(nameSpace + "." + entityTypeName); 
var foreignType = Type.GetType(nameSpace + "." + foreignTypeName); 
var names = foreignType.GetProperties() 
    .Where(p => typeof(ICollection<entityType>).IsAssignableFrom(p.PropertyType)) 
    .Select(p => p.Name); 
var foreignCollectionName = names.FirstOrDefault(); 

entityType 给出 "type or namespace unknown"当它在 <>

基于 Jon 和 Ani 的回复的解决方案

var foreignCollectionName = foreignType.GetProperties() 
    .Where(p => typeof(ICollection<>) 
        .MakeGenericType(entityType) 
        .IsAssignableFrom(p.PropertyType)) 
    .Select(p => p.Name).FirstOrDefault(); 

请您参考如下方法:

您需要通过反射查看属性。最简单的方法是使用 LINQ:

var names = typeOfB.GetProperties() 
                   .Where(p => p.PropertyType == typeof(desiredPropertyType)) 
                   .Select(p => p.Name);