简体   繁体   English

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

[英]Casting generic type with interface constraint

I have the following classes and interfaces 我有以下类和接口

public interface IFoo {}

public class Foo : IFoo {}

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

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

How can I cast Wrapper<Foo> to IWrapper<IFoo> ? 如何将Wrapper<Foo>投射到IWrapper<IFoo> An exception is raised when using Cast (InvalidCastException) as I get null when using as. 使用Cast(InvalidCastException)时引发异常,因为使用as时为null。

Thanks for the help! 谢谢您的帮助!

UPDATE UPDATE

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>;

I'm using .net 4.5. 我正在使用.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();

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 eg 注意,只有在IUserRepository定义中的输出位置中都出现out修饰符时,才可以将out修饰符添加到类型参数T中,例如

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
}

Wrapper<Foo> needs to be Wrapper<IFoo> . Wrapper<Foo>必须是Wrapper<IFoo> Then you should be able to cast it. 然后,您应该可以投射它。 And it needs to implement the interface too. 并且它也需要实现接口。

The cast below works... I don't think you can cast an objects generic type parameter to a different type (ie IWrapper<Foo> to IWrapper<IFoo> ). 下面的转换有效...我认为您不能将对象的泛型类型参数转换为其他类型(即IWrapper<Foo>IWrapper<IFoo> )。

void Main()
{
    var foo = new Wrapper();
    var t = foo as IWrapper<IFoo>;
    t.Dump();       
}


public interface IFoo {}

public class Foo : IFoo {}

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

public class Wrapper : IWrapper<IFoo> {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM