问题
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>
? An exception is raised when using Cast (InvalidCastException) as I get null when using as.
Thanks for the help!
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. Hope this helps.
回答1:
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
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
}
回答2:
Wrapper<Foo>
needs to be 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 (i.e. IWrapper<Foo>
to 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> {}
来源:https://stackoverflow.com/questions/17956407/casting-generic-type-with-interface-constraint