Today I saw a video on csdn to explain c#3.0, although the speaker a bit stuttering but I still insist on listening to finish. There's a phrase in it that I'm interested in, and if it's structurally identical we can do a strong turn on an anonymous type. It seems that at the critical moment we can still directly manipulate the anonymous type although it's a bit of a hassle.
We know that an anonymous type is actually a generic class that is automatically generated by. NET and uses the same anonymous type as long as the field name is the same type. So as long as the class uses this feature, we can make a strong turn of an anonymous type passed by parameter.
public T CastAnonymous<T>(object anonymous, T anonymousType)
{
return (T)anonymous;
}
class User
{
public string Name { get; set; }
}
public static void Main()
{
var u = new User{ Name = "Lucifer" };
var a = new { a = 26; u.Name; b = false };
Print(a);
}
public void Print(object anonymous)
{
var a = CastAnonymous(anonymous, new { a=0, Name = "", b = false });
Console.WriteLine{"{0} - {1} - {2}", a.a, a.Name, a.b};
}