微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有这样的界面:
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或继承它.

原文地址:https://www.jb51.cc/csharp/98780.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐