سؤال

Basically, what would be the equivalent of this but is 100% guaranteed to work?

 object x = new List<MyTypeWhichImplementsIInterface>();
 bool shouldBeTrue = x is IEnumerable<IInterface>;

From some rough testing it seems to work, but I'm not sure.

هل كانت مفيدة؟

المحلول

This will work in C# 4, but not in prior versions.

The is statement takes advantage of covariance for generic type parameters, a feature added in C# 4. Prior to C# 4, the statement would be false.

نصائح أخرى

It works because the IEnumerable<T> is actually IEnumerable<out T>. Without the variance-specifier on the <T> it wouldn't work.

So, as long as yout interface has correct variance specifiers, and as long as 'T' at both sides satisfy the type of the variance, it's ok.

If there are no in/out specifiers, then the T must match exactly for the cast to succeed, and the manual check presented by CSJ is the only option left.

x.GetGenericTypeDefinition() == typeof(IEnumerable<>) &&
typeof(IInterface).IsAssignableFrom(x.GetType().GetGenericArguments()[0]);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top