简体   繁体   中英

Constrain Type to Any Instance of Generic Type in C#

I want to create a base entity that I can use with multiple data access systems. The generic type argument represents the type of a property.

public interface IEntity<T> {
    public T Id {get; set;}
}

I want to be able to use this interface as a generic type constraint without having to specify a type parameter in a generic method.

public void Read<T>(Expression<Func<T, bool>> expression) where T : IEntity<**any type**>

Is this possible? If not, what are the alternatives?

You can do this. Add a second generic type parameter:

public void Read<T, U>(Expression<Func<T, bool>> expression) where T : IEntity<U>

Use a constraint on that type parameter and specify both types in the declare. This pushes the decision about what TOther is down the chain.

public void Read<T,TOther>(Expression<Func<T, bool>> expression) where T : IEntity<TOther>

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