因此,我正在为我的模型和项目中的服务创建接口。我创建的第一个接口是用于持久性实体的接口,我将其设置为通用类型,因为该实体可以具有类型为'int'或'Guid'的ID。
public interface IPersistentEntity<T>
{
T Id { get; set; }
}
此后,我继续为处理持久性实体的服务创建接口,最终这样。
public interface IPersistentEntityService<TPersistentEntity, T>
where TPersistentEntity : IPersistentEntity<T>
{
TPersistentEntity Get(T id);
}
现在,这很好用,我想知道是否可以通过设置接口的方式来解决ID类型,并自动考虑服务中使用的实体。
>使用代码,如果我想创建服务,就已经完成了。
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”),这是我希望以某种方式自动解决的问题。
这有可能吗?
答案 0 :(得分:0)
您想要的是以下内容吗?
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);
}