Why calling ISet.Contains() compiles, but throws an exception at runtime?

后端 未结 5 1864
时光取名叫无心
时光取名叫无心 2020-12-08 08:26

Please, help me to explain the following behavior:

dynamic d = 1;
ISet s = new HashSet();
s.Contains(d);

The

5条回答
  •  没有蜡笔的小新
    2020-12-08 08:44

    The Contains method is defined on ICollection, not ISet. The CLR doesn't allow an interface base method to be called from a derived interface. You usually doesn't see this with static resolution because the C# compiler is smart enough to emit a call to ICollection.Contains, not the non-existing ISet.Contains.

    Edit: The DLR mimics the CLR behavior, that's why you get the exception. Your dynamic call is done on an ISet, not an HashSet the DLR will mimics the CLR: for an interface, only interfaces methods are searched for, not base interfaces (contrary to classes where this behavior is present).

    For an in-depth explanation, see a previous response of mine to a similar question:

    Strange behaviour when using dynamic types as method parameters

提交回复
热议问题