Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

c# - Anonymous Types - Are there any distingushing characteristics?

Is there anything to use, to determine if a type is actually a anonymous type? For example an interface, etc?

The goal is to create something like the following...

//defined like...
public static T Get<T>(this IAnonymous obj, string prop) {
    return (T)obj.GetType().GetProperty(prop).GetValue(obj, null);
}
//...

//And then used like...
var something = new { name = "John", age = 25 };
int age = something.Get<int>("age");

Or is that just the beauty of an anonymous type? Nothing to identify it self because it takes a new shape?

Note - I realize that you can write an extension method for the object class, but that seems like a little overkill, in my opinion.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: The list below applies to C# anonymous types. VB.NET has different rules - in particular, it can generate mutable anonymous types (and does by default). Jared has pointed out in the comment that the naming style is different, too. Basically this is all pretty fragile...

You can't identify it in a generic constraint, but:

  • It will be a class (rather than interface, enum, struct etc)
  • It will have the CompilerGeneratedAttribute applied to it
  • It will override Equals, GetHashCode and ToString
  • It will be in the global namespace
  • It will not be nested in another type
  • It will be internal
  • It will be sealed
  • It will derive directly from object
  • It will be generic with as many type parameters as properties. (You can have a non-generic anonymous type, with no properties. It's a bit pointless though.)
  • Each property will have a type parameter with a name including the property name, and will be of that type parameter, e.g. the Name property becomes a property of type <>_Name
  • Each property will be public and read-only
  • For each property there will be a corresponding readonly private field
  • There will be no other properties or fields
  • There will be a constructor taking one parameter corresponding to each type parameter, in the same order as the type parameters
  • Each method and property will have the DebuggerHiddenAttribute applied to it.
  • The name of the type will start with "<>" and contain "AnonymousType"

Very little of this is guaranteed by the specification, however - so it could all change in the next version of the compiler, or if you use Mono etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...