开发者

Difference between property Users and IRepository.Users

开发者 https://www.devze.com 2023-04-11 12:06 出处:网络
I have an interface IRepository to abstract my repository. DbContext class is an Entity Framework to work with First Code.

I have an interface IRepository to abstract my repository. DbContext class is an Entity Framework to work with First Code.

public interface IRepository 
{
    IQueryable<User> Users { ge开发者_如何学JAVAt; }
}

public class Repository : DbContext, IRepository
{
    public DbSet<User> Users { get; set; }
    IQueryable<User> IRepository.Users { get{ return Users; } }
}

I did not understand the User property user in Repository class.

This code compiles, I wonder why.

What is the interface name before the name of the property?


This is valid syntax, called Explicit Interface Implementation. It's useful in 2 situations:

  • when you implement 2 interfaces with same method (check link above)
  • when you want to "hide" an implementation detail in a sense. In your example, if user will have DbContext reference, he will see DbSet<User> property and will be able to access it, on the other hand, if you will give your user only IRepository - he will only see IQueryable<User>, which let's you hide what's underneath it.

//Edit: Actually, one more usage that I personally like and used in my code as well:

  • you can hide some methods / properties but still implementg them. For example, Dictionary<K, V> implements ICollection<KeyValuePair<K, V>>, so it's ought to implement method with signature: void Add(KeyValuePair<K, V> kv), this one is ugly, you would prefer void Add(K key, V value), but you can't ignore the first one. With explicit int. impl. you can implement the first method, but hide it from user (at least as long as he won't cast Dictionary to ICollection).


The Users property in the Repository class has a different return type than that of the interface. To satisfy the requirements of the interface there is also an explicit implementation of the Users property from the IRepository interface.

You will find a more detailed discussion on explicit interface implementations here: implicit vs explicit interface implementation


Its the type, this property returns a generic Interface of IQueryable. Ie its a specific type of the Interface IQueryable, which has been created generically for user.

IQueryable is the interface but its a special version of the IQueryable interface which only accepts objects of type user.

Please see this introduction to generics http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号