C# is generic type with generic type constraint

好久不见. 提交于 2019-12-31 02:58:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!