简体   繁体   中英

Generic extension method for various types having the same properties

I am wondering, is it possible to create an extension method that will work with a set of different types provided they have the same property? For example:

public static T GetObjectByIdOrName<T>(this IEnumerable<T> collection, Mapping mapping) where T : IType1, IType2, IType3
    {
        return collection.FirstOrDefault(x => x.Id == mapping.ObjectId || x.Name == mapping.ObjectName);
    }

All Types have the Id and Name properties so I hoped this would be possible - however, the compiler is telling me that there is an ambiguous reference between Type1.Id and Type2 Id...

Is there any way to implement this? (I cannot create a common base for them)

It's fairly easy given proper code design. Just have them share a common interface.

public interface IBase
{
    object Id{ get; set; }
    string Name{ get; set; }
}

public interface IType1 : IBase{}
public interface IType2 : IBase{}

public static T GetObjectByIdOrName<T>(this IEnumerable<T> collection, Mapping mapping) where T : IBase
{
    //... get T.Id or T.Name
}

Otherwise, since there is no shared implementation implicit in the design, you can clumsily assume the properties will be there using dynamic.

public static object GetObjectByIdOrName(this IEnumerable collection, Mapping mapping)
{
    return collection.Cast<dynamic>().FirstOrDefault(x => x.Id == mapping.ObjectId || x.Name == mapping.ObjectName);
}

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