使用泛型的接口“不能隐式转换类型". [英] Interface using generics "Cannot implicitly convert type"

查看:227
本文介绍了使用泛型的接口“不能隐式转换类型".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个接受从IUser派生的泛型类型的类,我该如何避免出现此错误消息

If i have a class which accepts a generic type derived from IUser, how can i avoid this error message

不能将类型ElimCMS.Service.Users.someclass<ElimCMS.DataModel.Users.User>隐式转换为ElimCMS.Service.Users.Isomeclass<ElimCMS.DataModel.Users.IUser>.存在显式转换(您是否缺少演员表?)

Cannot implicitly convert type ElimCMS.Service.Users.someclass<ElimCMS.DataModel.Users.User> to ElimCMS.Service.Users.Isomeclass<ElimCMS.DataModel.Users.IUser>. An explicit conversion exists (are you missing a cast?)

示例

   public interface Isomeclass<TUser>
   where TUser : class, IUser
   {

    string test(TUser user);
    TUser returnUser();
   }

   public class someclass<TUser> : Isomeclass<TUser>
   where TUser : class, IUser, new()
   {
    public string test(TUser user)
    {
        string email = user.EMail;
        user.EMail = "changed:" + email;

        return email;
    }


    public TUser returnUser()
    {
        throw new NotImplementedException();
    }
}

 Isomeclass<ElimCMS.DataModel.Users.IUser> servicetest = new someclass<ElimCMS.DataModel.Users.User>();

推荐答案

之所以会发生这种情况,是因为具有不同类型的泛型彼此不兼容.为了解决这个问题,您可以使用将通用参数声明为Isomeclass是协变的

This happens because generics which have different types are not compatible with eachother. To get around this, you can declare your generic parameter to Isomeclass to be covariant using

public interface Isomeclass<out TUser>
   where TUser : class, IUser
{

    string test(TUser user);
    TUser returnUser();
}

但是,这将破坏test方法,因为它将不再是类型安全的.为了解决这个问题,您可以将参数user的类型更改为IUser,它将像以前一样工作.

However, this will break the test method since it will no longer be type safe. To get around this you can change the paramter user type to IUser and it will work as before.

这取决于您使用的C#版本.对于某些较旧的版本,无法将泛型声明为协变,这意味着您必须将分配目标更改为与分配给它的对象相同的类型.

This is dependent on the version of C# that you are using. For some older versions generics cannot be declared as covariant, which means you have to change the assignment target to be of the same type as the object you assign to it.

这篇关于使用泛型的接口“不能隐式转换类型".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆