How can be possible to use anonymous type fields without know them?
It is really looks 开发者_JS百科so cool to me how GridView's DataSource property gets anonymous type and shows results in Grid .
Simply
Grid.DataSource = from order in db.OrdersSet
select new { order.PersonSet.Name,order.PersonSet.SurName};
For example how can i write a propery or method which takes anonymous type and write field values to console output ?
The compiler actually creates (auto-generates) a class when it encounters syntax which use anonymous types, e.g.
var anonymousType = new { Name = "chibacity", Age = 21 };
This mechanism is automated by the compiler, but using a tool like Reflector you can disassemble the compiled code where you will see that a class has been generated to represent this anonymous type, e.g.:
[CompilerGenerated]
[DebuggerDisplay(@"\{ Name = {Name}, Age = {Age} }", Type="<Anonymous Type>")]
internal sealed class <>f__AnonymousType0<<Name>j__TPar, <Age>j__TPar>
{
// Fields
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly <Age>j__TPar <Age>i__Field;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly <Name>j__TPar <Name>i__Field;
// Methods
[DebuggerHidden]
public <>f__AnonymousType0(<Name>j__TPar Name, <Age>j__TPar Age);
[DebuggerHidden]
public override bool Equals(object value);
[DebuggerHidden]
public override int GetHashCode();
[DebuggerHidden]
public override string ToString();
// Properties
public <Age>j__TPar Age { get; }
public <Name>j__TPar Name { get; }
}
Update
Now that you have edited your question...
I am assuming that the question is that you desire to access the anonymous types outside of the scope it was declared in. This question is a duplicate of:
Accessing C# Anonymous Type Objects
Accessing C# Anonymous Type Objects
With reflection...
If you have an instance of an anonymous type, you can hold it in a variable of type object
, call GetType()
on it, and then GetFields
, GetProperties
, etc. to find out what columns are associated with it. Each PropertyInfo
or FieldInfo
you see has the capability to retrieve the value from any instance of the type.
Anonymous types are syntactic sugar in a way. The compiler analyses the output of such operations and creates classes on the fly with the properties you request. It simply takes work from you - before anonymous types, you had to write classes or structs for every type you used, even though they were just temporary information. With anonymous classes/methods/lambdas you don't have to do this anymore and save a lot of time.
You can do something like this:
private void button2_Click(object sender, EventArgs e)
{
var p = new { a = 10, b = 20 };
TestMethod(p);
}
private void TestMethod(object p)
{
Type t = p.GetType();
foreach (PropertyInfo pi in t.GetProperties())
{
System.Diagnostics.Debug.WriteLine(string.Format("{0} = {1}", pi.Name,
t.InvokeMember(pi.Name, BindingFlags.GetProperty, null, p, null)));
}
}
精彩评论