问题描述
因此,我正在为我的模型和项目中的服务创建接口.我创建的第一个接口是用于持久性实体的接口,我将其设置为通用类型,因为该实体可以具有类型为'int'或'Guid'的ID.
So I'm creating interfaces for my models and for my services in my project. The first interface I created was one for persistent entities, I set it up with a generic as the entity could have an Id of type 'int' or 'Guid'.
public interface IPersistentEntity<T>
{
T Id { get; set; }
}
此后,我继续为处理持久性实体的服务创建接口,最终这样.
After this, I went on to create the interface for the services that would deal with Persistent entities, which ended up like this.
public interface IPersistentEntityService<TPersistentEntity, T>
where TPersistentEntity : IPersistentEntity<T>
{
TPersistentEntity Get(T id);
}
现在,这很好用,我想知道是否可以通过一种方式来设置接口,以便在考虑到服务中使用的实体的情况下自动解决Id的类型.
Now, this works just fine, the thing is I'm curious if it is possible to set up the interface in a way where the type for the Id is solved automatically taking into account the entity used in the service.
使用代码,如果我想创建一个服务,我就已经做了类似的事情.
With the code, I've done if I want to create a service I would need to do something like this.
public partial class User : IPersistentEntity<int>
{
public int Id { get; set; }
}
public class UserService : IPersistentEntityService<User, int>
{
public User Get(int id)
{
throw new NotImplementedException();
}
}
我希望它像
public class UserService : IPersistentEntityService<User>
{
public User Get(int id)
{
throw new NotImplementedException();
}
}
注意,我将不再指示类中使用的类型(在这种情况下为"int"),这是我希望以某种方式自动解决的问题.
Note I would no longer be indicating the type used in the class ("int" in this case), which is the thing I would like to be resolved automatically somehow.
这有可能吗?
推荐答案
以下内容是否会满足您的需求?
Would something like the following do what you're looking for?
public class UserService : IPersistentEntityService<User, int>
{
public User Get<U>(U id)
{
Console.WriteLine(typeof(U));
return null;
}
}
public interface IPersistentEntityService<TPersistentEntity, T>
where TPersistentEntity : IPersistentEntity<T>
{
TPersistentEntity Get<U>(U id);
}
void Main()
{
UserService service = new UserService();
service.Get<int>(23);
}
这篇关于具有两个通用参数的接口,自动求解一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!