Can an anonymous type inherit from another type?

2019-06-16 10:49发布

问题:

According to the MSDN documentation on the StringComparer.OrdinalIgnoreCase property:

The OrdinalIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.

Is this a feature I'm unfamiliar with—anonymous types with inheritance? Or by "anonymous class" did the author simply mean "internal class deriving from StringComparer, not visible to client code"?

回答1:

If you look at the source code for StringComparer, you can see that OrginalIgnoreCase returns an instance of OrdinalComparer, which is derived from StringComparer.

There's nothing 'anonymous' about this that I can see, it's just that it's internal so you can't see it from outside the framework.



回答2:

It's not an anonymous type in the normal C# meaning of the term.

It's just a type which is internal, so you don't know the name of it: you can't refer to the exact type within your code.



回答3:

The compiler can create anonymous types that inherit from another type - you cannot. It's too bad, really as it would be a cool feature to create an anonymous type on the fly that either inherits from another class or implements an interface.



回答4:

Anonymous type is anonymous to us not the CLR and complier. Compiler uses a funny naming which includes <> in the name and only compiler can do that! and maybe Chuck Norris...