问题
Let's asume an interface
interface IOwnedBy<T> where T : IOwner
{
T Owner { get; }
}
and
interface IOwner
{
public int Id { get; }
}
Somewhere in my code, I would like to do the following:
if (obj is OwnedBy<IOwner>)
{
DoSomethingWith( obj.Owner.Id );
}
Basically, I want to check whether obj is any OwnedBy implementation. As IOwner is the type constraint of any generic parameter, I thought this one would work. But the condition is never met.
Any way without using alot of reflection?
回答1:
Change the interface to be covariant in T:
interface IOwnedBy<out T> where T : IOwner
{
T Owner { get; }
}
obj is OwnedBy<IOwner> fails because the compiler can't know if its safe; IOwnedBy is declared as invariant. If you explicitly tell the compiler that it is covariant, it then knows that the conversion is safe and it will work.
And why is it unsafe in a invariant interface? Consider the following:
interface IOwnedBy<T> where T : IOwner
{
T Owner { get; }
void SetOwner(T Owner);
}
class Person: IOwner { }
class Cat: IOwner { }
Cat tom = ...
IOwnedBy<Person> owned = ...
var nope = owned as IOwnedBy<IOwner>;
nope.SetOwner(tom); //Ouch! Just set a cat as an owner of a IOwnedBy<Person>
来源:https://stackoverflow.com/questions/45100710/c-sharp-is-generic-type-with-generic-type-constraint