具有接口约束的泛型类型转换 [英] Casting generic type with interface constraint

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

问题描述

我具有以下类和接口

public interface IFoo {}

public class Foo : IFoo {}

public interface IWrapper<T> where T : IFoo {}

public class Wrapper<Foo> : IWrapper<Foo> {}

我该如何投放 Wrapper< Foo> IWrapper< IFoo> ?使用Cast(InvalidCastException)时会引发异常,因为使用as时会为null。

How can I cast Wrapper<Foo> to IWrapper<IFoo>? An exception is raised when using Cast (InvalidCastException) as I get null when using as.

感谢帮助!

更新

这里是一个更具体的示例:

Here is a more concrete example:

public interface IUser {}

public class User : IUser {}

public interface IUserRepository<T> where T : IUser {}

public class UserRepository : IUserRepository<User> {}

现在,我需要能够执行以下操作:

Now I need to be able to do something like this:

 UserRepository up =  new UserRepository();
 IUserRepository<IUser> iup = up as IUserRepository<IUser>;

我正在使用.net 4.5。希望对您有所帮助。

I'm using .net 4.5. Hope this helps.

推荐答案

从您的编辑中,您实际上想要的是:

From your edit, you actually want:

public interface IUserRepository<out T> where T : IUser {}
public class UserRepository : IUserRepository<User> {}

然后您可以执行以下操作:

then you can do:

IUserRepository<IUser> iup = new UserRepository();

请注意,您只能添加 out 类型参数 T 的修饰符,如果它出现在 IUserRepository 的定义的输出位置中,例如

note you can only add add the out modifier to the type parameter T if it appears in the output position everywhere in the definition of IUserRepository e.g.

public interface IUserRepository<out T> where T : IUser
{
    List<T> GetAll();
    T FindById(int userId);
}

如果它出现在输入位置的任何位置,例如方法参数或属性设置器将无法编译:

if it appears anywhere in the input position, such as a method parameter or property setter it will fail to compile:

public interface IUserRepository<out T> where T : IUser
{
    void Add(T user);       //fails to compile
}

这篇关于具有接口约束的泛型类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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