简体   繁体   中英

How can I get the name of an ICollection<> property from a reference to the contained type?

I have type references A and B but I want the name of the ICollection<A> which is a property of B . How can I get the collection name "BunchOfX" if I only have the two types?

public class X
{
}

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

I need something that can give me the property name "BunchOfX" when all I have is the type references A and B. Let's say A will reference the type that the ICollection<> holds, and B will reference the type the ICollection<> is defined on.

The Real Code

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 gives "type or namespace unknown" when it is in the <>

Solution based on Jon and Ani's replies

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

You'd need to look through the properties with reflection. The easiest way to do this is using LINQ:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM