具有两个通用参数的接口,自动求解一个

编程入门 行业动态 更新时间:2024-10-26 15:17:37
本文介绍了具有两个通用参数的接口,自动求解一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此,我正在为我的模型和项目中的服务创建接口.我创建的第一个接口是用于持久性实体的接口,我将其设置为通用类型,因为该实体可以具有类型为'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); }

更多推荐

具有两个通用参数的接口,自动求解一个

本文发布于:2023-06-08 03:51:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/576133.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   参数   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!