加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在C#界面中返回Type T?

发布时间:2020-12-15 18:31:36 所属栏目:百科 来源:网络整理
导读:我有这样的界面: public interface IUser{ //some properties here T ToDerived(User u);} 我是接口开发的新手,所以这就是我想要完成的.我会有一个基类 public class User 不实现上述接口.然后我将有一个派生类 SalesUser : User,IUser{ //no properties ne
我有这样的界面:
public interface IUser{
    //some properties here

    T ToDerived(User u);
}

我是接口开发的新手,所以这就是我想要完成的.我会有一个基类

public class User

不实现上述接口.然后我将有一个派生类

SalesUser : User,IUser
{
    //no properties needed because they exist in the User class

    SalesUser ToDerived(User u)
    {
        //code for converting a base User to a derived SalesUser
    }
}

我想在SalesUser类中编写ToDerived(User u)的函数,但是在界面中,我不知道如何定义这个,因为我现在在界面中的ToDerived方法声明没有编译.

我希望这是有道理的.

解决方法

public interface IUser<T> where T : User
{
    //some properties here

    T ToDerived(User u);
}

SalesUser : User,IUser<SalesUser>
{
    //no properties needed because they exist in the User class

    SalesUser ToDerived(User u)
    {
        //code for converting a base User to a derived SalesUser
    }
}

不确定这是你想要的,但是我在接口上添加了泛型类型约束,以确保泛型类型是User或继承它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读