具有接口约束的泛型类型转换

Her*_*nan 0 c# generics casting interface

我有以下类和接口

public interface IFoo {}

public class Foo : IFoo {}

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

public class Wrapper<Foo> : IWrapper<Foo> {}
Run Code Online (Sandbox Code Playgroud)

我怎样才能投Wrapper<Foo>IWrapper<IFoo>?使用Cast(InvalidCastException)时引发异常,因为使用as时为null。

谢谢您的帮助!

更新

这是一个更具体的示例:

public interface IUser {}

public class User : IUser {}

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

public class UserRepository : IUserRepository<User> {}
Run Code Online (Sandbox Code Playgroud)

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

 UserRepository up =  new UserRepository();
 IUserRepository<IUser> iup = up as IUserRepository<IUser>;
Run Code Online (Sandbox Code Playgroud)

我正在使用.net 4.5。希望这可以帮助。

Lee*_*Lee 5

通过编辑,您实际上想要:

public interface IUserRepository<out T> where T : IUser {}
public class UserRepository : IUserRepository<User> {}
Run Code Online (Sandbox Code Playgroud)

那么您可以执行以下操作:

IUserRepository<IUser> iup = new UserRepository();
Run Code Online (Sandbox Code Playgroud)

注意,仅当将out修饰符添加到类型参数中T时,才可以将其添加到type参数中,IUserRepository例如,

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

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

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